我在 UITableViewCell 中以编程方式创建了几个 UIButton,并在 layoutSubviews
中设置了它的框架。我也在这里设置选中状态。
但是,这似乎不是创建按钮状态或初始化按钮状态的最佳位置,因为 layoutSubviews
被多次调用。我可以在哪里放置以下代码,使框架正确,但只会初始化一次?
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width / 2.0, self.frame.size.height)];
button.selected = YES
我的一个想法是在 awakeFromNib
中初始化所有一次性设置,然后在 layoutSubviews
中进行实际的帧设置。这是一个好的方法吗?
最佳答案
如果您将 NIB 文件用于您的自定义 UITableViewCell
然后上课awakeFromNib
是您应该初始化 UIElements、类属性和 UITableViewCell
的其他实例变量的方法类。
否则,如果您使用自定义 UITableViewCell
class without a NIB 那么你应该初始化
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialize your frames here
}
return self;
}
现在,如果你想用不同的按钮状态或数据更新你的单元格,那么你只需从
- tableView:cellForRowAtIndexPath:
并为该特定单元格更改任何您想要的内容。
例如:
- tableView:(UITableView *)tableView cellForRowAtIndecPath:(NSIndexPath *)indexPath {
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
[cell someMethod];
return cell;
}
关于ios - 如何在 UITableViewCell 中获得正确的框架并且只初始化一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29189980/