【问题标题】:Why isn't initWithCoder initializing items correctly?为什么 initWithCoder 不能正确初始化项目?
【发布时间】:2012-08-09 05:50:04
【问题描述】:

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

我读到我应该为此使用initWithCoder。我的 initWithCoder 函数正在被调用,我可以单步执行函数中的每一行,它似乎正在执行动作。但是,当我运行我的应用程序时,我看不到任何正在应用的属性。最明显的是,字体没有改变。我只是认为我在UILabels 上修改的任何属性实际上都没有被保存或显示。

我将此子类与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

还有标题:

#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

【问题讨论】:

    标签: objective-c ios xcode uistoryboard initwithcoder


    【解决方案1】:

    当您收到消息时,您的任何 IBOutlets 均未设置 - 您需要使用“awakeFromNib”或“viewDidLoad”(类似的东西)来访问您的网点。也就是说,您可以在 initWithCoder 中设置其他非出口的东西。

    【讨论】:

    • 哦,好的。用awakeFromNib 替换initWithCoder 似乎可以按预期工作。非常感谢!
    • 虽然,看起来awakeFromNib 发生在我在cellForRowAtIndexPath 中设置我的任何属性之前。这让我觉得也许我的实例方法是更好的方法,因为我可以根据UILabel 等中的当前文本可靠地执行调整大小操作。
    • 顺序应该是:initWithCoder、awakeFromNib、cellForRowAtIndexPath。如果您需要“预设”一些数学值,您可以在 init 例程中进行。但是在加载笔尖之前,您无法访问您的插座。
    猜你喜欢
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    相关资源
    最近更新 更多