initWithFrame 和 initWithCoder

本文介绍在iOS开发中,如何不使用XIB文件而是通过代码来初始化视图控制器的方法。包括使用initWithFrame方法创建自定义视图控制器,并阐述了加载nib文件时如何使用initWithCoder进行对象实例化。

 当我们所写的程序里没用用Nib文件(XIB)时,用代码控制视图内容,需要调用initWithFrame去初始化

- (id)initWithFrame:(CGRect)frame

{

    if (self =[superinitWithFrame:frame]) {

        // 初始化代码

    }

    return self;

}


用于视图加载nib文件,从nib中加载对象实例时,使用 initWithCoder初始化这些实例对象

- (id)initWithCoder:(NSCoder*)coder

{

    if (self =[superinitWithcoder:coder]) {

        // 初始化代码

    }

    return self;

}


帮我解释一下下面代码:// #import "TPBLabel.h" #pragma mark -overrides @implementation TPBLabel - (instancetype)initWithFrame:(NSRect)frameRect { self = [super initWithFrame:frameRect]; if (self) { [self setupInitialData]; [self configure]; } return self; } - (instancetype)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; if (self) { [self setupInitialData]; [self configure]; } return self; } - (void)setupInitialData { self.font = self.defaultFont; self.textColor = self.defaultTextColor; self.backgroundColor = self.defaultBackgroundColor; self.numberOfLines = 1; self.textAlignment = NSTextAlignmentNatural; self.lineBreakMode = NSLineBreakByTruncatingTail; } - (void)configure { self.editable = NO; self.selectable = NO; self.bezeled = NO; self.drawsBackground = NO; self.usesSingleLineMode = NO; self.font = self.font; self.textColor = self.textColor; self.alignment = self.textAlignment; self.maximumNumberOfLines = self.numberOfLines; self.lineBreakMode = self.lineBreakMode; self.backgroundColor = self.backgroundColor; [self setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal]; } - (NSSize)intrinsicContentSize { if (TPBIsEmptyString(self.text)) { return CGRectZero.size; } else { return [super intrinsicContentSize]; } } - (NSFont*)defaultFont { return [NSFont tpr13Regular]; } - (NSColor*)defaultTextColor { return [NSColor tpTextPrimary]; } - (NSColor*)defaultBackgroundColor { return [NSColor clearColor]; } #pragma mark - #pragma mark setters which invalidate the view - (NSString *)text { return self.stringValue; } - (void)setText:(NSString *)text { if (text != nil) { self.stringValue = text; } } - (NSAttributedString *)attributedText { return self.attributedStringValue; } - (void)setAttributedText:(NSAttributedString *)attributedText { if (attributedText != nil) { self.attributedStringValue = attributedText; } } - (void)setTextAlignment:(NSTextAlignment)textAlignment { _textAlignment = textAlignment; self.alignment = _textAlignment; } - (void)setNumberOfLines:(NSInteger)numberOfLines { _numberOfLines = numberOfLines; self.maximumNumberOfLines = numberOfLines; } @end
09-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值