如何引用UITableViewCell里面的UIView

时间:2016-06-22 20:12:54

标签: objective-c xcode uitableview

我在其中一个表格视图中有一个uiview。我想知道如果像这样引用它(它100%工作)是正确的。如果没有,请告诉我正确的方法。

基本上,我现在正在做的是将uiview分配给cellForRowAtIndexPath内的实例变量。

这样的事情:

myViewReference = cell.myView;

之后,改变我的ivar属性也会改变单元格内部uiview的属性,因此它可以很好地工作。

这是做这样的事情的好方法吗?

1 个答案:

答案 0 :(得分:0)

这取决于您UITableView的设置方式

  • 如果是动态原型,强烈的做法并不好 引用它作为UITableViewCell s在滚动时可重复使用。更好的方法是使用viewWithTag方法获取myViewReference

例如:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    UIView *myViewReference = [cell viewWithTag:1000];
    // If you don't use storyboard and init myViewReference programmatically then do this:
    if (!myViewReference) {
        myViewReference = [[UIView alloc] initWithFrame:cell.contentView.bounds];
        myViewReference.tag = 1000;
        [cell.contentView addSubview:myViewReference];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // Get your UITableViewCell by identifying its indexPath.
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UIView *myViewReference = [cell viewWithTag:1000];
    [myViewReference doSomething];

}
  • 如果是静态单元格,那么从中获取强大的参考资料就完全没问题了。您可以拖放IBOutlet的{​​{1}}并通过以下方式获取:myViewReference