IOS/Objective-C:在自定义 Tableview 单元格中检测按钮按下?

use*_*314 1 objective-c uitableview custom-cell ios

对于提要视图控制器,我有一个带有一些自定义单元格的表格视图,这些单元格具有用于点赞、评论和分享的按钮,我想根据按下的按钮执行不同的操作。

我最初的想法是简单地将故事板中自定义单元格中的按钮连接到自定义单元格中的操作方法。但是,我对自定义单元格 .m 文件中的方法如何与视图控制器中的 TableView 交互感到困惑。

- (IBAction)likeButtonPressed:(id)sender {
 CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
//do something
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以澄清是否可以在情节提要中连接单元格中的按钮,以及这如何与视图控制器、cellforrowatindexpath 和 didselectrowatindexpath 上的委托方法一起播放?

或者,如果这不是正确的方法,将不胜感激任何关于更好方法的建议。在此先感谢您的任何建议。

PGD*_*Dev 6

而不是使用delegateor tags,您可以简单地使用blocks来做到这一点。Blocksdelegate模式和推荐使用更容易和简单。

Swift太,你将看到的广泛使用closures (blocks in Objective-C)比任何其他模式。

例子:

1.UITableViewDataSource方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.likeButtonTapHandler = ^{
        NSLog(@"Like Button Tapped");
        //ADD YOUR CODE HERE
    };
    cell.commentButtonTapHandler = ^{
        NSLog(@"Comment Button Tapped");
        //ADD YOUR CODE HERE
    };
    cell.shareButtonTapHandler = ^{
        NSLog(@"Share Button Tapped");
        //ADD YOUR CODE HERE
    };
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

2.自定义UITableView Cell

@interface TableViewCell : UITableViewCell

@property (nonatomic, copy) void(^likeButtonTapHandler)(void);
@property (nonatomic, copy) void(^commentButtonTapHandler)(void);
@property (nonatomic, copy) void(^shareButtonTapHandler)(void);

@end

@implementation TableViewCell

- (IBAction)likeButtonTapped:(UIButton *)sender
{
    self.likeButtonTapHandler();

}

- (IBAction)commentButtonTapped:(UIButton *)sender
{
    self.commentButtonTapHandler();
}

- (IBAction)shareButtonTapped:(UIButton *)sender
{
    self.shareButtonTapHandler();
}
Run Code Online (Sandbox Code Playgroud)