以下实现正常,但它不是最优雅的解决方案。 是否有任何最佳实践或不同的实现来确定是否在自定义UITableViewCell上使用UIButton?
- (IBAction)customCellButtonTapped:(id)sender {
UIButton *button = (UIButton *)sender;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
// Set the value of the object and save the context
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TTCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
[self configureCell:cell atIndexPath:indexPath];
[cell.customCellButton addTarget:self action:@selector(customCellButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[cell.customCellButton setTag:indexPath.row];
return cell;
}
答案 0 :(得分:2)
我同意它不够优雅。由于要重复使用单元格,因此必须更改按钮标记以保持同步。更不用说,标签可能是真正需要的,这不是告诉代码视图的行。
这是我在tableviews中一直使用的包含控件的方法:
- (NSIndexPath *)indexPathOfSubview:(UIView *)view {
while (view && ![view isKindOfClass:[UITableViewCell self]]) {
view = view.superview;
}
UITableViewCell *cell = (UITableViewCell *)view;
return [self.tableView indexPathForCell:cell];
}
现在,在
- (IBAction)customCellButtonTapped:(id)sender {
NSIndexPath *indexPath = [self indexPathOfSubview:sender];
// use this to access your MOC
// or if we need the model item...
id myModelItem = self.myModelArray[indexPath.row];
// or if we need the cell
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
答案 1 :(得分:1)
如果您已经拥有该单元的子类,则可以始终实现所有者实现的协议,例如:
@protocol TTCustomCellDelegate <NSObject>
- (void)customCellWasTapped:(TTCustomCell *)cell withSomeParameter:(id)parameter;
@end
@interface TTCustomCell : UITableViewCell
@property (nonatomic, weak) id<TTCustomCellDelegate> delegate;
@end
@implementation
- (void)buttonWasTapped
{
if(self.delegate)
[self.delegate customCellWasTapped:self withSomeParameter:whateverYouNeed];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
cell.delegate = self;
...
}
- (void)customCellWasTapped:(TTCustomCell *)cell withSomeParameter:(id)parameter
{
id thing = cell.somePropertyUniqueToThisCell;
id otherThing = parameter;
}