【问题标题】:Custom View with Xib as root View以 Xib 作为根视图的自定义视图
【发布时间】:2019-09-04 18:25:33
【问题描述】:

创建自定义视图时,是否可以将根视图设置为xib?

目前,如果我创建自定义视图,我需要将笔尖添加为子视图。

如果我想更改背景颜色,我将无法再使用 UIView API。

customView.backgroundColor = UIColor.red // Won't work because nib view is covering the "root" view.

那么,有没有可能做到这一点..

class CustomView: UIView {

    func commonInit() {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: getInheritedClassName(object: type(of: self)), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        // Currently doing this..
        addSubview(view)
        // Can we do this somehow?
        self = view // Set self as the xib view
    }
}

【问题讨论】:

    标签: ios swift xib nib


    【解决方案1】:

    使用 awakeAfter:

    open override func awakeAfter(using _: NSCoder) -> Any? {
        // set the tag in the view's XIB, so we don't create an infinite loop
        guard tag != 999 else {
            return self
        }
    
        let view = type(of: self).instantiate() // Convenience method that chooses nib based on class name
        view.frame = frame
        view.autoresizingMask = autoresizingMask
        view.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints
        view.tag = tag
        for constraint in constraints {
            let firstItem = constraint.firstItem as? UIView == self ? view : constraint.firstItem
            let secondItem = constraint.secondItem as? UIView == self ? view : constraint.secondItem
            let constraintToAdd = NSLayoutConstraint(item: firstItem as Any, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: secondItem, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant)
            constraintToAdd.priority = constraint.priority
            view.addConstraint(constraintToAdd)
        }
    
        return view
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多