Lohith Korupolu Lohith Korupolu - 11 months ago 58
Swift Question

subviews userinteraction when superview userinteraction disabled swift

I would like to keep subviews (UITextFields in this case) still active (editable in usual way i.e. tap on the textField and a keyboard appears) while the parent view which is a UITableViewCell's userInteractionEnabled is set to false.

Explaining further -
1. There is a UITableViewCell initialized from a xib.

  1. Inside this cell, I have three UITextFields and a UIButton.

  2. On some condition, I need to disable the cell interaction (to avoid the didSelectRowAtIndexPath) - this part, I do not have any problem.

  3. After step 3, all the subViews inside the cell are getting disabled as well.

  4. But I need to enter some text inside the textFields and tap the button with some action to it.

What I did so far:
1. Used userInteractionEnabled and set it to false for the cell -

myPersonalInfoExpandedCell.userInteractionEnabled = false

2. Two textFields firstNameText and lastNameText, I enabled userInteraction and set it firstNameText to becomeFirstResponder

(myPersonalInfoExpandedCell as! PersonalInfoExpandedCell).firstNameText.userInteractionEnabled = true
(myPersonalInfoExpandedCell as! PersonalInfoExpandedCell).lastNameText.userInteractionEnabled = true
(myPersonalInfoExpandedCell as! PersonalInfoExpandedCell).firstNameText.becomeFirstResponder()

Problem is, for the textFields, the
is not working which I suspect because of
is false for the TableViewCell.
is working for
but I need interaction to all the UI Elements inside the cell.

How can we do that? Please could someone help?

Answer Source

To disable the cellSelection implement the willSelectRowAtIndexPath delegate method and return nil for the cells that you do not want to select. You say that you want to disable selection under some conditions, so I assume that you have the indexPaths for the rows for which you want to disable selection. Just return nil for these indexPaths. See the following code.

-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
if (indexPath == self.MyIndex) //Check for the index path for the cell you want to disable selection for
   return nil;
   return indexPath;

Also do this to prevent the cell from highlighting.

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

Doing it this way you do not have to setUserInteractionEnabled:NO on the cell. This way when you tap on the cell the didSelectRowAtIndexPath delegate method won't get called and your textFields would still be enabled


Following is the swift version of the above code

func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if (indexPath == self.MyIndex) //Check for the index path for the cell you want to disable selection for
    return nil;
    return indexPath;

cell.selectionStyle = .None