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

前端 未结 5 1841
野的像风
野的像风 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条回答
  •  猫巷女王i
    2021-01-29 20:50

    Here is how I do a Subview on iOS in Swift -

    class CustomSubview : UIView {
    
        init() {
            super.init(frame: UIScreen.mainScreen().bounds);
    
            let windowHeight : CGFloat = 150;
            let windowWidth  : CGFloat = 360;
    
            self.backgroundColor = UIColor.whiteColor();
            self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
            self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);
    
            //for debug validation
            self.backgroundColor = UIColor.grayColor();
            print("My Custom Init");
    
            return;
        }
    
        required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
    }
    

提交回复
热议问题