Swift subclass UIView

后端 未结 6 1831
时光说笑
时光说笑 2020-12-07 10:49

I want to subclass UIView and show a login like view. I\'ve created this in Objective-C, but now I want to port it to Swift. I do not use storyboards, so I crea

6条回答
  •  -上瘾入骨i
    2020-12-07 11:25

    Swift 4.0,If you want to use view from xib file, then this is for you. I created CustomCalloutView class Sub class of UIView. I have created a xib file and in IB just select file owner then select Attribute inspector set class name to CustomCalloutView, then create outlet in your class.

        import UIKit
        class CustomCalloutView: UIView {
    
            @IBOutlet var viewCallout: UIView! // This is main view
    
            @IBOutlet weak var btnCall: UIButton! // subview of viewCallout
            @IBOutlet weak var btnDirection: UIButton! // subview of viewCallout
            @IBOutlet weak var btnFavourite: UIButton! // subview of viewCallout 
    
           // let nibName = "CustomCalloutView" this is name of xib file
    
            override init(frame: CGRect) {
                super.init(frame: frame)
                nibSetup()
            }
    
            required init?(coder aDecoder: NSCoder) {
                super.init(coder: aDecoder)
                nibSetup()
            }
    
            func nibSetup() {
                Bundle.main.loadNibNamed(String(describing: CustomCalloutView.self), owner: self, options: nil)
                guard let contentView = viewCallout else { return } // adding main view 
                contentView.frame = self.bounds //Comment this line it take default frame of nib view
               // custom your view properties here
                self.addSubview(contentView)
            }
        }
    

    // Now adding it

        let viewCustom = CustomCalloutView.init(frame: CGRect.init(x: 120, y: 120, 50, height: 50))
        self.view.addSubview(viewCustom)
    

提交回复
热议问题