Idiomatic template for initializing UIViews in Swift

In Objective-CI developed a template containing both a method awakeFromNiband initWithFrame:one that called them superand then called _commonInitwhere I put all my own code. For instance.

- (void)_commonInit {
    // Initialize stuff here
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self _commonInit];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self _commonInit];
}

So, I'm trying to reuse this template in my subclasses of UIView, which I port to Swift:

func _commonInit() {
    // initialize code here
}

override init(frame:CGRect) {
    super.init(frame:frame)
    self._commonInit()
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func awakeFromNib() {
    super.awakeFromNib()
    self._commonInit()
}

Is this the right thing to do? I'm curious why init(coder...) required. Especially when all I do is call the version super. I, it seems, remember that the reason I used awakeFromNibin the version Objcwas that any changes applied in restoring nib did not happen earlier than initFromCoder:.

+4
1

commonInit, , , ( ) . .

( )...

  • init(coder:) , , NSCoding. , .

    init(coder:), encodeWithCoder(_:). , , , ( , , super).

  • awakeFromNib() , nib/, , , .

    Cocoa (Touch) , ( init(coder:)), "", IBOutlet IBAction, . awakeFromNib().

  • - commonInit Swift: (, ) super.init(), self ( self), super.init(). , commonInit, .

    , . nil, "" commonInit:

    var name: String!
    init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }
    init(coder: NSCoder) {
        super.init(coder: coder)
        self.commonInit()
    }
    private func commonInit() {
        name = // something...
    }
    

, , ( ) . , commonInit, , init ( , ).

class MyView: UIView {
    let fileManager = NSFileManager.defaultManager()
    let appDelegate = UIApplication.sharedApplication().delegate as! MyAppDelegate
    lazy var name: String = { /* compute here */ }()
    init(frame: CGRect) { super.init(frame: frame) }
    init(coder: NSCoder) { super.init(coder: coder) }
    // ...
}

, commonInit ( ), - : Swift , , , , private.

+4

All Articles