Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access different views inside of a UITableViewCell by tag in Swift

I'm trying to make an app for iOS 8, using swift. The goal here is to make a kind of news feed. This feed displays posts from users, which follows a certain pattern.

I thought of using the UITableView where each cell follows a custom layout. The problem appears when I try to access a text label inside it. I try to access it by its tag, but when I do it, the whole app crashes. The error reported is "Swift dynamic cast failed", and I'm using the following code to access the view:

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

    let cellId: String = "cell"

    var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId) as UITableViewCell

    if let ip = indexPath{
        cell.textLabel.text = myData[ip.row] as String
        var lbl = cell.contentView.viewWithTag(0) as UILabel
        lbl.text = "ola"
    }

    return cell
}

Am I doing something wrong? Thanks in advance!

like image 765
flapas Avatar asked Aug 28 '14 17:08

flapas


2 Answers

i think the Problem is the Tag 0. All Views are on default value 0. So try another tag value.

like image 196
derdida Avatar answered Oct 30 '22 17:10

derdida


Just faced the same issue. The solution was to change tag to 10 and 20. I used 1 and 2 before. Is anybody aware of a range of tags that is used by the system?

So my 'cellForRowAtIndexPath' for a table with an image and a label per row looks like this now:

internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier") as? UITableViewCell {
        (cell.contentView.viewWithTag(10) as UIImageView).image = IMAGES[indexPath.row]
        (cell.contentView.viewWithTag(20) as UILabel).text = LABELS[indexPath.row]

        return cell
    } else {
        NSLog("Prototype did not work")
        return UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "errorIdentifier")
    }
}
like image 31
jboi Avatar answered Oct 30 '22 16:10

jboi