我正在尝试向我的表添加一个背景视图,该视图的大小应该可以扩展,以便在旋转时始终填充表的框架。为了简化这个问题,我只是试图将一个红色的UIVIew
添加到表视图中,然后使用自动布局,以确保红色视图始终填充整个可见背景。如果我不实现自动布局,在旋转时,你可以看到红色不再填充屏幕上的可见区域。但当我使用下面的代码实现自动布局时,红色视图在屏幕上不再可见。我只看到默认的表视图backgroundColor
。为什么,我的自动布局代码出了什么问题?
UIView *view = [[UIView alloc] initWithFrame:self.tableView.frame];
view.backgroundColor = [UIColor redColor];
[self.tableView addSubview:view];
[self.tableView sendSubviewToBack:view];
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.tableView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.tableView
attribute:NSLayoutAttributeTop
multiplier:1
constant:0]];
[self.tableView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.tableView
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0]];
[self.tableView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self.tableView
attribute:NSLayoutAttributeLeading
multiplier:1
constant:0]];
[self.tableView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:self.tableView
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:0]];
您应该对表视图使用backgroundView属性。只需使用alloc-init创建视图(不需要框架或约束),并将该视图设置为表视图的背景视图
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor redColor];
self.tableView.backgroundView = view;
除非你的单元格是透明的,否则你不会看到这个视图,除非你把视图向下拉或滚动到底部。