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

前端 未结 5 1884
野的像风
野的像风 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:12

    Swift 5 Solution

    You can try out this implementation for running Swift 5 on XCode 11

    
    class CustomView: UIView {
    
        var customParam: customType
        
        var container = UIView()
        
        required init(customParamArg: customType) {
            self.customParam = customParamArg
            super.init(frame: .zero)
            // Setting up the view can be done here
            setupView()
        }
    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
    
        func setupView() {
            // Can do the setup of the view, including adding subviews
    
            setupConstraints()
        }
        
        func setupConstraints() {
            // setup custom constraints as you wish
        }
        
        
    }
    
    
    

提交回复
热议问题