如何正确初始化自定义UITableviewCell?

Mic*_*all 29 initialization objective-c uitableview ios

我使用以下两种方法返回自定义单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *key = [self keyForIndexPath:indexPath];
    UITableViewCell *cell;

    if ([key isEqualToString:DoneButtonCellKey]) {
        cell = [self [self doneButtonCellForIndexPath:indexPath];
        return cell;
    } else {
        //code to return default cell...
    }
} 
Run Code Online (Sandbox Code Playgroud)

然后:

- (DoneButtonCell *)doneButtonCellForIndexPath: (NSIndexPath *)indexPath {

    DoneButtonCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DoneButtonCellIdentifier forIndexPath:indexPath];
    return cell;

}
Run Code Online (Sandbox Code Playgroud)

在这里使用单元格的正确init方法是什么,所以我可以在初始化时更改单元格的某些属性?

编辑:我发现了问题,因为没有为我调用init/awakeFromNib方法.我追踪了错误,并且我没有将"自定义类"从UITableViewCell更改为我的自定义类.现在,awakeFromNib和initWithCoder的工作方式如下所述.

Mos*_*erg 36

您可以在DoneButtonCell课堂上进行更改

- (void)awakeFromNib
{
 .. essential to call super ..
 super.awakeFromNib()
 //Changes done directly here, we have an object
}
Run Code Online (Sandbox Code Playgroud)

initWithCoder:方法:

-(id)initWithCoder:(NSCoder*)aDecoder
{
   self = [super initWithCoder:aDecoder];

   if(self)
   {
     //Changes here after init'ing self
   }

   return self;
}
Run Code Online (Sandbox Code Playgroud)

  • 在我的案例中,这些都没有被调用 (5认同)

TAL*_*ALE 5

如果您正在使用Swift,请记住确保在创建视图时初始化视图的简单方法是使用didSet方法.例如,要将UIImageView转换为圆形,您可以添加如下代码:

@IBOutlet weak var profileImageView: UIImageView! {
    didSet {
        // Make the profile icon circle.
        profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2
        profileImageView.clipsToBounds = true
    }
}
Run Code Online (Sandbox Code Playgroud)