Assign xib to the UIView in Swift

前端 未结 9 1965
死守一世寂寞
死守一世寂寞 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:28

    for Swift 4

    extension UIView {
        class func loadFromNibNamed(nibNamed: String, bundle: Bundle? = nil) -> UIView? {
          return UINib(
              nibName: nibNamed,
              bundle: bundle
          ).instantiate(withOwner: nil, options: nil)[0] as? UIView
      }
    }
    

    for Swift 3

    You could create an extension on UIView:

    extension UIView {
        class func loadFromNibNamed(nibNamed: String, bundle: NSBundle? = nil) -> UIView? {
            return UINib(
                nibName: nibNamed,
                bundle: bundle
            ).instantiateWithOwner(nil, options: nil)[0] as? UIView
        }
    }
    

    Note: Using UINib is faster because it does caching for you.

    Then you can just do:

    ViewDetailItem.loadFromNibNamed("ViewBtnWishList")
    

    And you will be able to reuse that method on any view.

提交回复
热议问题