我做了一个 UIView
的子类,它有一个固定的框架。那么,我可以只覆盖 init
而不是 initWithFrame:
吗?例如:
- (id)init {
if ((self = [super initWithFrame:[[UIScreen mainScreen] bounds]])) {
self.backgroundColor = [UIColor clearColor];
}
return self;
}
-initWithFrame:
的 Xcode 文档说:“如果您以编程方式创建 View 对象,则此方法是 UIView
类的指定初始化程序。子类可以覆盖此方法方法来执行任何自定义初始化,但必须在其实现开始时调用 super
。”
“指定初始化器”是什么意思?
最佳答案
指定构造器是所有其他构造器必须调用的构造器。 UIView
和子类有点不寻常,因为它们实际上有两个这样的初始化器:-initWithFrame:
和 -initWithCoder:
,具体取决于如何 View 已创建。如果在代码中实例化 View ,则应覆盖 -initWithFrame:
,如果从 nib 加载 View ,则应覆盖 -initWithCoder:
。或者,您可以将代码放在第三种方法中并覆盖这两个初始化程序,以便它们调用您的第三种方法。事实上,这通常是推荐的策略。
因此,例如,您可以创建一个 UIView 子类 ClueCharacter
,它有自己的初始化方法:-initWithPerson:place:thing:
。然后,您可以像这样创建 View :
objective-C :
ClueCharacter *mustard = [[ClueCharacter alloc] initWithPerson:@"Col. Mustard"
place:kInTheStudy
thing:kTheRope];
swift :
var mustard = ClueCharacter("Col. Mustard", place: kInTheStudy, thing: kTheRope)
没关系,但是为了初始化对象的 UIView 部分,您的方法必须调用指定的初始化程序:
objective-C :
-(id)initWithPerson:(NSString*)name place:(CluePlace)place thing:(ClueWeapon)thing
{
if ((self = [super initWithFrame:CGRectMake(0, 0, 150, 200)])) {
// your init stuff here
}
}
swift :
func init(name: String, place : CluePlace, thing : ClueWeapon)
{
if (self = super.init(CGRectMake(0, 0, 150, 200))) {
// your init stuff here
}
}
如果你想调用子类的初始化器-init
,只要在实现中调用-initWithFrame:
就可以了。
关于iOS: UIView 子类 init 或 initWithFrame:?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7126726/