使用表头视图的子类中的ViewWithTag控制父表视图

时间:2014-05-16 03:42:00

标签: ios objective-c uitableview uiview

我有一个表的标题视图的UIView子类,是否可以使用viewWithTag:从我的标题视图子类中获取表视图?我试过以下方法,但仍然一无所获:

我的方法1:

UIView *tv = (UIView *)[self.superview viewWithTag:11];

我的方法2:

UITableView *tv = (UITableView *)[self.superview viewWithTag:11];

感谢。

2 个答案:

答案 0 :(得分:0)

最佳解决方案是走到视图的超级视图层次结构,直到进入表格视图。无论基础表视图结构如何,此方法都将起作用。

UIView *view = self.superview;
UITableView *tv = nil;
while (view) {
    if ([view isKindOfClass:[UITableView class]]) {
        tv = (UITableView *)view;
        break;
    }
    view = view.superview;
}

if (tv) {
    // found the table view. Do something with it
}

答案 1 :(得分:0)

创建您的UITableView:

 TableHeaderView *v = [[TableHeaderView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
_tableView.tableHeaderView = v;
// I think you miss this line
_tableView.tag = 101; 
_tableView.backgroundColor = [UIColor redColor];
NSLog(@"%@",_tableView.backgroundColor); 
// value: UIDeviceRGBColorSpace 1 0 0 1

在TableHeaderView中:

- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
    // just example to get super class
    [self performSelector:@selector(doSomething) withObject:nil afterDelay:5];
}
return self;
}

- (void) doSomething
{
UITableView *tb = (UITableView*) [self.superview viewWithTag:101];
NSLog(@"%@",tb.backgroundColor);
// value: after:UIDeviceRGBColorSpace 1 0 0 1
}