如何克服UITableViewCell子类限制

时间:2014-08-12 16:53:21

标签: ios objective-c uitableview

我有一个自定义uitableviewcellsubclassed,它包含一个uitextfielddelegate也已设置,现在按下键盘上的return key时我想尝试一些事情

  1. 执行一个segue(但问题是我在uitableviewcell子类中)。
  2. 以模态方式呈现另一个视图控制器(但问题是uitableviewcell 不允许这样做。)
  3. 我想显示uiactionsheet(但是再次限制是 的UITableViewCell)。
  4. 如果我获得rootviewcontroller引用,则rootviewcontroller的视图本身不会显示或不显示活动视图,因此您执行的任何操作都不会显示在屏幕上,因此需要活动视图。

3 个答案:

答案 0 :(得分:2)

您可以在单元格上使用块属性,只要发生自定义按钮操作,就会触发该属性。您的单元格的块属性可能如下所示:

@interface CustomTableViewCell : UITableViewCell

@property (nonatomic, copy) void (^customActionBlock)();

@end

然后,您的单元格将从自定义按钮操作中调用此块,如下所示:

@implementation CustomTableViewCell

- (IBAction)buttonTapped:(id)sender {
    if ( self.customActionBlock ) {
        self.customActionBlock();
    }
}

@end

最后,您将-cellForRowAtIndexPath:中的块设置回视图控制器(或任何位置),如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"customCell" forIndexPath:indexPath];
    cell.textLabel.text = [self.colors objectAtIndex:indexPath.row];
    cell.customActionBlock = ^{
        NSLog(@"Do the stuff!");
        // present view controller modally
        // present an action sheet
        // etc....
    };
    return cell;
}
但是,有一点需要注意。如果使用块,则存在强烈引用self并创建内存泄漏的风险。块很有趣且易于使用,但你必须遵守他们的规则。以下是一些可以帮助您熟悉它们的资源:

答案 1 :(得分:1)

您可以将操作添加到按钮,即使它们位于tableView

[cell.button addTarget:self action:@selector(presentController:) forControlEvents:UIControlEventTouchUpInside];

presentController指的是IBAction

- (IBAction)presentController:(id)sender
{
  //present
}

答案 2 :(得分:1)

在Tableview SuperClass中实现按钮操作。 或者您可以在UITableViewCell子类中使用自定义委托。在UITableView子类中声明一个协议。

@protocol customCellDelegate <NSObject>

@required
-(void)selectedButtonInIndexPath : (NSIndexPath *)indexpath;
@end

在UITableView子类

中设置此属性
@property (nonatomic, strong)NSIndexPath *indexpath;
@property (nonatomic, strong) id <customCellDelegate> delegate;

然后在您的UITableView子类按钮操作中添加此行

 if(self.delegate){
    [self.delegate selectedButtonInIndexPath: self.indexpath];
 }

在tableview数据源方法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

实施此代码

cell.delegate = (id)self;
cell.indexpath = indexPath;

在Uitableview超级类中只需实现此方法

 -(void)selectedButtonInIndexPath : (NSIndexPath *)indexpath{
    //display uiimagepickercontroller modally or anything else here
 }
相关问题