Correct way to load a Nib for a UIView subclass

前端 未结 6 1931
挽巷
挽巷 2020-11-29 18:36

I am aware this question has been asked before but the answers are contradicting and I am confused, so please don\'t flame me.

I want to have a reusable UIView

6条回答
  •  独厮守ぢ
    2020-11-29 19:06

    In Swift:

    For example, name of your custom class is InfoView

    At first, you create files InfoView.xib and InfoView.swiftlike this:

    import Foundation
    import UIKit
    
    class InfoView: UIView {
        class func instanceFromNib() -> UIView {
        return UINib(nibName: "InfoView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
    }
    

    Then set File's Owner to UIViewController like this:

    Rename your View to InfoView:

    Right-click to File's Owner and connect your view field with your InfoView:

    Make sure that class name is InfoView:

    And after this you can add the action to button in your custom class without any problem:

    And usage of this custom class in your MainViewController:

    func someMethod() {
        var v = InfoView.instanceFromNib()
        v.frame = self.view.bounds
        self.view.addSubview(v)
    }
    

提交回复
热议问题