Assign xib to the UIView in Swift

2019-01-08 06:01发布

in objective c it can be done in init method by

-(id)init{
    self = [[[NSBundle mainBundle] loadNibNamed:@"ViewBtnWishList" owner:0 options:nil]     objectAtIndex:0];
return self;
}

but when i do this in swift

init(frame: CGRect) {
    self = NSBundle.mainBundle().loadNibNamed("ViewDetailMenu", owner: 0, options: nil)[0] as? UIView
}

cannot assign to self in a method error is shown. now my approach is to create a view, and add the view loaded from nib to it. anyone have a better idea?

标签: uiview swift xib
8条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-08 06:40

I think this is the easies but also the cleanest way to assign a xib to a UIView. Xcode 7.3 and swift 2.0.

import UIKit

//Create CustomView class
class CustomView: UIView {

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

//Use it
let customView = CustomView.instanceFromNib() as! CustomView
查看更多
Ridiculous、
3楼-- · 2019-01-08 06:41

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

enter image description here

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

enter image description here

That's it

and use

enter image description here

查看更多
登录 后发表回答