iOS:UIView子类init或initWithFrame:?

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:实现就可以了.

  • 我的理解是只有一个初始化器(指定的初始化器)应该1)调用超类的指定初始化器,2)包含初始化逻辑.任何其他初始化器应该调用指定的初始化器(在这种情况下:`[self initWithPerson:nil place:nil thing:nil]`)._Further_,应重写超类的指定初始值设定项以调用新的指定初始值设定项. (3认同)
  • @LeeFastenau一般情况下,只有一个指定的初始值设定项,但它并不总是*真.如上所述,可以使用`-initWithFrame:`或`-initWithCoder:`初始化视图,并且这两个视图都不会调用另一个视图.因此,在视图的情况下,确实有两个指定的初始值设定项.另请参阅[`-initWithFrame:`]的文档(https://developer.apple.com/library/IOs/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/initWithFrame :). (2认同)

小智 23

UIView呼唤[super init]中完全等于[super initWithFrame:CGRectZero]