[英]iOS: Passing object to custom UITableViewCell to UIViewController via a button action on cell
我有一个自定义UITableViewCell
,上面有一个按钮,即IB链接到一个名为:
- (IBAction)clickUse:(id)sender;
在此函数中,我计划在用户单击UITableViewCell
上的按钮时,将一个对象从UITableView
的数据源( NSMutableArray
一个对象)传递到下一个UIViewController
。
我在自定义UITableViewCell
设置了一个属性,如下所示:
@property (nonatomic, retain) SomeObject *some_object;
在UITableView
的cellForRowAtIndexPath
函数中,我将对象传递给单元格:
MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
cell.some_object = [self.cellData objectAtIndex:indexPath.row];
此时,我跟踪对象,它仍然在这里。 但是在MyCustomCell
单元格中,对象消失了并分配给nil
。 因此,该对象不能传递给下一个UIViewController
。
我错过了什么?
也许最好使用其他方法。 您可以给每个单元格按钮一个标签。 标签值可以是行索引路径。
您的-tableView:cellForRowAtIndexPath:方法可以包括以下内容:
MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
cell.button.tag = indexPath.row
您的-clickUse:方法可能如下所示:
- (IBAction)clickUse:(id)sender
{
UIButton *button = (UIButton *)sender;
SomeObject *object = [self.cellData objectAtIndex:button.tag];
// do stuff with your object on click
}
我建议创建一个委托协议来处理此问题。 在单元格上定义一个委托。 在您的cellForRowAtIndexPath:
方法中,将cell.delegate
设置为实现该方法的viewController
。 确保在单元的dealloc
和prepareForReuse
方法prepareForReuse
委托prepareForReuse
。 我认为,这是在涉及的对象之间建立最干净关系的解决方案。 请参见下面的示例。
将按钮目标分配给某个对象,而不是按钮的超级视图,这总是与我的直觉相反。 或者,每当我在一个有这样的设置的代码库上工作时,我都会发现它最终会妨碍/混淆事物。
内部CommentCell.h:
@class Comment;
@class SMKCommentCell;
@protocol SMKCommentCellDelegate <NSObject>
@required
- (void)commentCellDidTapShowReplies:(SMKCommentCell *)cell;
- (void)commentCellDidTapUsername:(SMKCommentCell *)cell;
@end
@interface SMKCommentCell : UITableViewCell
@property (nonatomic, strong) Comment *comment;
@property (nonatomic, weak) id<SMKCommentCellDelegate> delegate;
@end
内部CommentCell.m:
#pragma mark - Actions
- (IBAction)didTapShowReplies:(id)sender
{
if ([self.delegate respondsToSelector:@selector(commentCellDidTapShowReplies:)])
{
[self.delegate commentCellDidTapShowReplies:self];
}
}
- (IBAction)didTapUsername:(id)sender
{
if ([self.delegate respondsToSelector:@selector(commentCellDidTapUsername:)])
{
[self.delegate commentCellDidTapUsername:self];
}
}
在您的viewController.m中:
#pragma mark - SMKCommentCell Delegate
- (void)commentCellDidTapShowReplies:(SMKCommentCell *)cell
{
// Do something
}
- (void)commentCellDidTapUsername:(SMKCommentCell *)cell
{
// Do something
}
在cellForRowAtIndexPath内部:
commentCell.comment = comment;
commentCell.delegate = self;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.