Access to various views inside a UITableViewCell by tag in Swift

I am 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 who follow a specific pattern.

I was thinking about using a UITableView, where each cell follows a custom layout. The problem occurs when I try to access a text label inside it. I try to access it by its tag, but when I do this, the entire application crashes. The reported error is "Swift dynamic cast failed" , and I use 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!

+6
source share
2 answers

I think the problem is tag 0. All views are by default 0. So try a different tag value.

+8
source

Just ran into the same problem. The solution was to change the tag to 10 and 20. I used 1 and 2 before. Does anyone know about the range of tags that are used by the system?

So my "cellForRowAtIndexPath" for a table with an image and a label in a row looks like this:

 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") } } 
+2
source

Source: https://habr.com/ru/post/974504/


All Articles