如何在uitableviewcell中添加uiview

Zee*_*bok 3 objective-c uitableview

希望你们所有人都没事.我的申请中有一点问题.我有自定义单元格的tableview.在我的定制单元课上,我做了一个uiview

    UIView* cellView = [[UIView alloc] initWithFrame:self.contentView.frame];
    cellView.backgroundColor = [UIColor grayColor];
    [self.contentView addSubview:cellView];
Run Code Online (Sandbox Code Playgroud)
问题是uiview不适合我的细胞框架.Cellforrow如下:

- (SummaryViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    SummaryViewCell *cell = (SummaryViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell == nil)
    {
        cell = [[SummaryViewCell alloc] init];
    }
    
    cell.backgroundColor = [UIColor blueColor];
  return cell;
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过initWithFrame:self.contentView.frame]但是同样的问题发生了(uiview出现在单元格中,但只覆盖了一半的单元格),我也尝试过cellView = [[UIView alloc] initWithFrame:CGRectMake(0,0,self. frame.size.width和高度相同但是失败了.需要您宝贵的建议和想法.非常感谢.

小智 5

你在哪里创建子视图?尝试在-layoutSubviews方法中执行此操作.

- (void)layoutSubviews {
    [super layoutSubviews];

UIView* cellView = [[UIView alloc] initWithFrame:self.contentView.frame];
    cellView.backgroundColor = [UIColor grayColor];
    [self.contentView addSubview:cellView];
}
Run Code Online (Sandbox Code Playgroud)

子视图的所有帧都已在此方法中计算,您应该为子视图接收正确的width\height.