How do I write a custom init for a UIView subclass in Swift?

前端 未结 5 1840
野的像风
野的像风 2021-01-29 20:48

Say I want to init a UIView subclass with a String and an Int.

How would I do this in Swift if I\'m just subclassing

5条回答
  •  长情又很酷
    2021-01-29 21:16

    Here is how I do it on iOS 9 in Swift -

    import UIKit
    
    class CustomView : UIView {
    
        init() {
            super.init(frame: UIScreen.mainScreen().bounds);
    
            //for debug validation
            self.backgroundColor = UIColor.blueColor();
            print("My Custom Init");
    
            return;
        }
    
        required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
    }
    

    Here is a full project with example:

    • UIView Example Project (with SubView example)

提交回复
热议问题