使用故事板时自定义uitableviewcell

时间:2014-01-15 15:41:36

标签: ios objective-c uitableview uistoryboard

我正在使用故事板进行我的项目,并且我正在尝试实现自定义UITableViewCell

我想在自定义单元格中执行以下操作:

#import "CustomCell.h"

@implementation CustomCell

@synthesize myLabel, myButton;

- (instancetype)initWithCoder:(NSCoder *)decoder
{
    if ((self = [super initWithCoder:decoder]))
    {
       //want to custom setup of properties placed in the cell
       self.myButton.backgroundColor = [UIColor redColor];//this does NOT work
       //and so forth... 
    }
    return self;
}

但是没有设置背景颜色。它仅在我在tableViewController的{​​{1}}函数中设置按钮的背景颜色时才有效,如下所示

cellForRowAtIndexPath

我通过设置断点和- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomCell"]; MyObject *obj = self.myObjects[indexPath.row]; cell.myButton.backgroundColor = [UIColor redColor];//This works! cell.myLabel.text = obj.name; return cell; } 尝试调试,NSLoginitWithCoder之前为每个单元调用? 但是当我在自定义单元格中设置时,单元格中按钮的背景颜色不会显示。

有任何帮助吗?

1 个答案:

答案 0 :(得分:3)

尝试使用awakeFromNib方法而不是initWithCoder:来对单元格进行任何初始自定义。正如评论中所提到的,对于像控件的背景颜色这样的简单事物,你可以通过故事板在Xcode中做到这一点。

相关问题