Assign xib to the UIView in Swift

前端 未结 9 1959
死守一世寂寞
死守一世寂寞 2020-11-30 20:11

in objective c it can be done in init method by

-(id)init{
    self = [[[NSBundle mainBundle] loadNibNamed:@\"ViewBtnWishList\" owner:0 options:nil]     obje         


        
9条回答
  •  粉色の甜心
    2020-11-30 20:19

    The true Swift approach is the use of protocols and protocol extensions.

    I use it like this: To start I create a protocol

        protocol XibInitializable {
            static var name: String { get }
            static var bundle: Bundle? { get }
    
            static func fromXib() -> Self
        }
    

    then I make a default implementation of this protocol use protocol extention

    extension XibInitializable where Self : UIView {
        static var name: String {
            return String(describing: Self.self)
        }
    
        static var bundle: Bundle? {
            return nil
        }
    
        static func fromXib() -> Self {
            return UINib(nibName: name, bundle: bundle).instantiate(withOwner: nil, options: nil)[0] as! Self
        }
    }
    

    the implementation of our protocol is now complete

    In order for this protocol to work, you need the name of our xib file and the class were the same. For example, for example

    finally add the protocol and make your class "final", like here.

    That's it

    and use

提交回复
热议问题