ma1*_*w28 37 subclass init uikit uiview ios
我做了一个UIView具有固定框架的子类.那么,我可以覆盖init而不是initWithFrame:吗?例如:
- (id)init {
if ((self = [super initWithFrame:[[UIScreen mainScreen] bounds]])) {
self.backgroundColor = [UIColor clearColor];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
Xcode文档-initWithFrame:说:"如果以编程方式创建视图对象,则此方法是类的指定初始化程序UIView.子类可以重写此方法以执行任何自定义初始化,但必须super在其实现开始时调用."
"指定初始化程序"是什么意思?
Cal*_*leb 73
指定的初始化程序是所有其他初始化程序必须调用的初始化程序.UIView他们实际上有两个这样的初始化器,-initWithFrame:并且-initWithCoder:,取决于视图的创建方式,它们有点不同寻常.-initWithFrame:如果要在代码中实例化视图,并且-initWithCoder:从nib加载它,则应该覆盖.或者,您可以将代码放在第三种方法中,并覆盖这些初始化程序,以便它们调用第三种方法.事实上,这通常是推荐的策略.
因此,例如,您可以创建一个UIView子类ClueCharacter,它有自己的初始化方法:-initWithPerson:place:thing:.然后,您可以像这样创建视图:
OBJ-C:
ClueCharacter *mustard = [[ClueCharacter alloc] initWithPerson:@"Col. Mustard"
place:kInTheStudy
thing:kTheRope];
Run Code Online (Sandbox Code Playgroud)
迅速:
var mustard = ClueCharacter("Col. Mustard", place: kInTheStudy, thing: kTheRope)
Run Code Online (Sandbox Code Playgroud)
这没关系,但是为了初始化对象的UIView部分,你的方法必须调用指定的初始化器:
OBJ-C:
-(id)initWithPerson:(NSString*)name place:(CluePlace)place thing:(ClueWeapon)thing
{
if ((self = [super initWithFrame:CGRectMake(0, 0, 150, 200)])) {
// your init stuff here
}
}
Run Code Online (Sandbox Code Playgroud)
迅速:
func init(name: String, place : CluePlace, thing : ClueWeapon)
{
if (self = super.init(CGRectMake(0, 0, 150, 200))) {
// your init stuff here
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想调用子类的初始化程序-init,只要你调用-initWithFrame:实现就可以了.