Assign xib to the UIView in Swift

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

    Just subclass this simple class (swift 5):

    open class NibView: UIView {
    
        open override func awakeAfter(using coder: NSCoder) -> Any? {
            if subviews.count == 0 {
                return UINib(nibName: "\(Self.self)", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
            }
            return self
        }
    }
    
    class CustomView: NibView {
    }
    

    As others pointed out, set File's Owner to your CustomView class (not xib's root view itself). Then set custom class to CustomView to any view that you want to be replaced by your custom view class. Also, autolayout respects all constraints inside your xib, at least as a subview of a UITableViewCell's content view. Not sure about other cases.

    As simple, as it happens to be, somehow Apple did another quest for us for such a basic thing! What a wonderful company! Never gonna be bored with them!

提交回复
热议问题