Conditional segue performed on tap on UITableViewCell

前端 未结 4 2102
悲&欢浪女
悲&欢浪女 2020-12-13 23:58

I\'m working on some project for iOS 5 using Xcode 4.2. I have one UITableViewController and want to perform a segue when user tap on table cell, but destination view contro

4条回答
  •  忘掉有多难
    2020-12-14 00:45

    I'm adding an extra answer just because after reading the selected one above in many places other than this - and it is the correct answer - I found myself wondering how to detect the touch that would ordinarily trigger the segue. You see, if you create your segue the usual way by ctrl-dragging from the table view cell to the next controller, then two things are done for you automatically.

    1. the touch in the cell is detected
    2. the segue is performed

    but of course, you can't block the segue.

    Now if you want to conditionally segue, then (as mentioned in the other answers) you delete that segue and create a new one from the UITableViewController (drag it from the objects navigator rather than the storyboard) to the next controller - and give it a name.

    Then - and this is the part I was missing - implement tableView:didSelectRowAtIndexPath in your table view controller to perform the segue programmatically and conditionally, as below.

    Note that you also need to identify your cell somehow so you know if the one you're interested in has been selected. You could do that by knowing the index path in a static table, but I prefer to set my cells unique identifier in IB (even though I don't need it for dequeueing since it's a static table) and checking it. That way if I move my cell up or down in the static table, I won't need to change this code.

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // Find the selected cell in the usual way
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
        // Check if this is the cell I want to segue from by using the reuseIdenifier
        // which I set in the "Identifier" field in Interface Builder
        if ([cell.reuseIdentifier isEqualToString:@"CellIWantToSegueFrom"]) {
    
        // Do my conditional logic - this was the whole point of changing the segue
        if (myConditionForSegueIsSatisfied) {
            // Perform the segue using the identifier I was careful to give it in IB
            // Note I'm sending the cell as the sender because that's what the normal
            // segue does and I already had code counting on that
            [self performSegueWithIdentifier:@"SegueIdentifer" sender:cell];
        }
    }
    

    Note how I send the cell with the segue - the normal segue from the cell does that, and I had originally passed nil, and my code which had depended on it stopped working.

提交回复
热议问题