【问题标题】:Adding subview to static UITableViewCell not working将子视图添加到静态 UITableViewCell 不起作用
【发布时间】:2015-05-11 20:40:34
【问题描述】:

我有一个static UITableView。我正在尝试以编程方式将UISegmentedControl 添加到第三个单元格。代码如下:

UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:@[@"First", @"Second"]];
segment.frame = CGRectMake(0, 0, 50, 30);

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]];
[cell.contentView addSubview:segment];

调用代码时,不会添加SegmentedControl

然后我尝试添加UILabel,但这也不起作用。

我不能把它放在那个方法中,因为我在选择按钮时添加了 SegmentedControl

【问题讨论】:

    标签: ios objective-c uitableview static addsubview


    【解决方案1】:

    当您拥有静态tableView 时,您可以将插座直接连接到其单元格并像简单的子视图一样进行操作。所以只需连接插座并使用您的代码添加子视图。它会工作

    更新

    使用以下代码添加子视图:

    [cell addSubview:segment];
    

    【讨论】:

    • 这是唯一的方法吗?我不能以编程方式做到这一点?
    • 这是最简单的。你甚至可以在 storyboard/xib 中添加 SegmentedControl
    • 我更新了答案,给contentView添加子视图不正确
    • 所以我的意思是你可以使用你的代码,但不要将子视图添加到contentView,而是直接添加到cell
    【解决方案2】:

    将代码移入

    - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    }
    

    然后只引用方法传递的cell

    【讨论】:

    • 我不能把它放在那个方法中,因为我在选择 button 时添加了 SegmentedControl
    • 哦,好的,您应该将其作为附加信息添加到您的问题中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多