UITableViewCell可伸缩的backgroundView

时间:2013-05-29 15:49:27

标签: ios objective-c uitableview

我有UITableView个可变高度的单元格。我宁愿不必使用背景图片,而是希望设置backgroundView具有我想要的样式。目前,我无法弄清楚如何根据单元格的高度动态更改backgroundView的高度。

- (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;
}

现在,背景视图只是重叠,因为它们没有调整大小:

enter image description here

这可能吗?

2 个答案:

答案 0 :(得分:1)

您可能希望执行类似

的操作,而不是设置背景视图的框架
UIView *view = [[UIView alloc] initWithFrame:cell.contentView.bounds];
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

此答案假设您没有使用自动布局,因为您正在设置背景视图的框架。如果您正在使用自动布局,则根本不想设置框架,而是在背景视图上设置约束。

答案 1 :(得分:0)

通常,您可以使用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];