carmelo carmelo - 5 months ago 27
Swift Question

Set action for subview inside a table cell (swift)

Here is my code.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("idcell", forIndexPath: indexPath) as UITableViewCell
let lblTitle : UILabel = cell.contentView.viewWithTag(101) as! UILabel
lblTitle.text = (deptId[indexPath.row] as? String)! + " " + (deptDesc[indexPath.row] as? String)!
var height:CGFloat = 40
if(indexPath.row == departmentSelectedRow){
for i in 0...deptProfile.count-1{
let label = UILabel(frame: CGRectMake(0,height,400,30))
label.targetForAction("sadasdd", withSender: nil)
height = height+40
label.text = ("ewrewrewre")
label.backgroundColor = UIColor.redColor()
return cell

Question: When i clicked the subview,it didn't trigger subview's action. But i have selected whole cell. How to fix it?


If you want to interact with something inside a cell (rather than select the whole cell) then you should use a button or a gesture recogniser. These are properly interactive elements that you can add a target and action to.

You should also change how you're using cells, specifically:

  1. Use custom cell classes, so you can directly reference the cell elements instead of using viewWithTag which is bad practice
  2. Use multiple different cell classes (and thus identifiers) so you can use actually different cells for selected and unselected rows
  3. Don't create and add subviews on the fly, this is what the different cell classes are for