UITableViewCell可伸缩背景查看
问题描述:
我有一个UITableView
可变高度单元格。我宁愿不必使用背景图像,而是想用我想要的样式设置backgroundView
。目前,我无法弄清楚如何根据单元的高度动态改变我的backgroundView
的高度。UITableViewCell可伸缩背景查看
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 60)];
view.backgroundColor = [UIColor whiteColor];
view.layer.cornerRadius = 2.0;
view.layer.shadowColor = [UIColor blackColor].CGColor;
view.layer.shadowOffset = CGSizeMake(0, 1);
view.layer.shadowRadius = 0.4;
view.layer.shadowOpacity = 0.2;
[cell.contentView addSubview:view];
[cell.contentView sendSubviewToBack:view];
}
ZSSLog *log = [self.items objectAtIndex:indexPath.row];
cell.textLabel.text = log.logText;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:15.0];
cell.textLabel.textColor = [UIColor grayColor];
return cell;
}
眼下的背景观点正好在同一时间,因为他们没有被调整:
这可能吗?
答
而不是设置你的背景框架来看,你可能想要做像
UIView *view = [[UIView alloc] initWithFrame:cell.contentView.bounds];
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
这个答案假设你不使用自动布局,因为你设置的背景视图的框架。如果你使用自动布局,你根本不想设置框架,而是在背景视图上设置约束。
答
通常情况下,您会使用backgroundView
属性。尝试建立你的背景图是这样的:
UIView *view = [[UIView alloc] initWithFrame:cell.bounds];
view.frame = UIEdgeInsetsInsetRect(view.frame, UIEdgeInsetsMake(0, 10, 0, 10));
view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
//...other cell config...
cell.backgroundView = view;
但如果你真的想要把contentView
内这种观点,你可以这样做:
UIView *view = [[UIView alloc] initWithFrame:cell.contentView.bounds];
view.frame = UIEdgeInsetsInsetRect(view.frame, UIEdgeInsetsMake(0, 10, 0, 10));
view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
//...other cell config...
[cell.contentView addSubview:view];
不,不使用自动布局或任何IB的一部分。这工作!只需要自动调整代码。谢谢! –