为什么initWithCoder没有正确初始化项目?

Rya*_*yan 19 xcode objective-c ios initwithcoder uistoryboard

我有一个子类UITableViewCell.我的子类包含几个UILabels.我希望我的子类将这些标签初始化为适用于我的每个表视图单元的某些默认设置.

我读到我应该用initWithCoder它.我的initWithCoder函数正在被调用,我可以逐步浏览我的函数中的每一行,它似乎经历了这些动作.当我运行我的应用程序时,我没有看到任何属性被应用.最值得注意的是,字体没有被更改.我只是不认为我正在修改的任何属性UILabel实际上是被保存或显示的.

我正在使用这个子类与a Storyboard.我知道我的更改不会反映在Storyboard,但是在应用程序运行时它们也没有反映出来 - 尽管我的代码正在执行.

编辑:我想提一下,在尝试覆盖之前initWithCoder,我在这些子类中有一个实例方法,我将运行此逻辑.我只是在其中调用该实例方法cellForRowAtIndexPath.这个方法很有效,但我认为在这个子类中自动生成这个逻辑会很方便.

有任何想法吗?我的代码如下:

#import "ThreadListCell.h"

@implementation ThreadListCell

- (id)initWithCoder:(NSCoder *)aDecoder {

    if ((self = [super initWithCoder:aDecoder])) {

        // adjust the font settings of the title
        self.title.font = [UIFont fontWithName:@"SourceSansPro-Black" size:16];
        self.title.textColor = [UIColor colorWithWhite:0.267f alpha:1.0f];

        // adjust the font settings of the subtitle
        self.text.font = [UIFont fontWithName:@"SourceSansPro-Light" size:14];
        self.text.textColor = [UIColor colorWithWhite:0.267f alpha:0.9f];
        self.text.textColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:1];

        // adjust the font settings of the location
        self.location.font = [UIFont fontWithName:@"SourceSansPro-Light" size:8];
        self.location.textColor = [UIColor colorWithWhite:0.267f alpha:0.9f];

        // adjust the UILabel settings of the title
        self.title.numberOfLines = 0;
        self.title.lineBreakMode = UILineBreakModeTailTruncation;

        // adjust the UILabel settings of the subtitle
        self.text.numberOfLines = 0;
        self.text.lineBreakMode = UILineBreakModeTailTruncation;

        // adjust the UILabel settings of the location
        self.location.numberOfLines = 0;
        self.location.lineBreakMode = UILineBreakModeTailTruncation;
        self.location.textAlignment = UITextAlignmentRight;

    }

    return self;

}

@end
Run Code Online (Sandbox Code Playgroud)

标题:

#import <UIKit/UIKit.h>

@interface ThreadListCell : UITableViewCell

@property (nonatomic, weak) IBOutlet UILabel *text;
@property (nonatomic, weak) IBOutlet UILabel *title;
@property (nonatomic, weak) IBOutlet UILabel *location;

@end
Run Code Online (Sandbox Code Playgroud)

Dav*_*d H 45

当您收到消息时,您的IBOutlet都没有设置 - 您需要使用"awakeFromNib"或"viewDidLoad" - 类似的东西 - 来访问您的网点.也就是说,您可以在initWithCoder中设置其他非插座内容.

  • 顺序应该是:initWithCoder,awakeFromNib,cellForRowAtIndexPath.如果需要"预设"一些数学值,可以在init例程中执行.但是在装入笔尖之前,您无法访问您的插座. (3认同)