gpt4 book ai didi

IOS/objective-C : Detect Button Press in Custom Tableview Cell?

转载 作者:行者123 更新时间:2023-12-01 17:36:07 25 4
gpt4 key购买 nike

对于提要 View Controller ,我有一个带有一些自定义单元格的表格 View ,这些单元格具有用于喜欢、评论和分享的按钮,我想根据按下的按钮执行不同的操作。

我最初的想法是简单地将 Storyboard 中自定义单元格中的按钮连接到自定义单元格中的操作方法。但是,我对自定义单元 .m 文件中的方法如何与 View Controller 中的 TableView 交互感到困惑。

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

谁能澄清一个单元格中的按钮是否可以连接到 Storyboard 中,以及它如何与 View Controller 、cellforrowatindexpath 和 didselectrowatindexpath 上的委托(delegate)方法一起使用?

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

最佳答案

而不是使用 delegatetags ,您可以简单地使用 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;
}

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();
}

关于IOS/objective-C : Detect Button Press in Custom Tableview Cell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47002156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com