Use UITableViewCell as Button

2019-02-19 10:16发布

I read some similar questions about this on Stack Overflow, but none of them had a satisfying answer.

What I am trying to achieve is a "Facebook Sign In Button" from the Settings screen.

Facebook Settings Screen

I want to achieve this using Static Cells. But I soon discovered that I could not connect a "Action" to the UITableViewCell using Xcode.

I then tried to achieve the same result using a Custom UITableViewCell with a UIButton inside, but it resulted it a lot of extra styling trouble to make it look exactly like a real UITableViewCell.

Now I managed to make the UITableViewCell to behave like a Button using the following solution:

I changed the Identifier of the "Login Button" UITableViewCell to "loginButton". And I added the following code to the Table View Controller.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([[selectedCell reuseIdentifier] isEqualToString:@"loginButton"]) {
        NSLog(@"Clicked");
        // Execute function to run code for Login button
    }
}

Instead of executing a IBAction (which would have been the case if I could just link it like a button in Xcode) I am now going to execute a Function.

This is working like expected. But the reason I created this question is: I want to know if this is the right way to go. Is this ok? Is this bad? Why is this ok or bad? Is there a better solution? Thanks!

1条回答
beautiful°
2楼-- · 2019-02-19 10:40

Thats a reasonable way to go.

A similar solution using indexpaths would be:

Create an outlet for the Table View Cell from IB.

@property (strong, nonatomic) IBOutlet UITableViewCell *loginButtonCell;

Then implement the didSelectRowAtIndexPath: method.

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath       *)indexPath
{
    if ([indexPath isEqual:[tableView indexPathForCell:self.loginButtonCell]])
    {
        // This will get called when you cell button is tapped
    }
}

You can then re-order and without having to modify your code

查看更多
登录 后发表回答