使用xib嵌套@IBDesignables?

时间:2017-11-29 12:05:03

标签: ios autolayout ibdesignable

我尝试在iOS上创建基于组件的系统,并且我想执行以下操作:

  1. 创建一个" PaddedView"在任何添加的子组件周围具有8px空间的组件,如容器类型组件。

  2. 在故事板上将另一个IBDesignable视图添加到此PaddedView中,并查看两个渲染。

  3. 这可能吗?

    目前,我正在使用以下超类来为所有IBDesignable组件加载来自xib的视图:

    import Foundation
    import UIKit
    
    @IBDesignable
    class SKDesignableView: UIView {
        var view: UIView?
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            self.loadXib()
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.loadXib()
        }
    
        func loadXib() {
            self.view = self.viewFromXib()
            self.view!.frame = self.bounds
            self.view!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
            self.addSubview(self.view!)
        }
    
        func viewFromXib() -> UIView {
            let bundle = UINib(nibName: String(describing: self.getType()), bundle: Bundle(for: self.getType()))
            let views = bundle.instantiate(withOwner: self, options: nil)
            return views.first as! UIView
        }
    
        func getType() -> AnyClass {
            fatalError()
        }
    }
    

    如何为其他IBDesignables创建占位符?

1 个答案:

答案 0 :(得分:0)

视图最初包含子视图,因此将容器视图作为子视图添加到需要子视图的任何组件。

func loadXib() {
        var subview: UIView? = nil
        if self.subviews.count > 0 {
            subview = self.subviews[0]
        }
        subview?.removeFromSuperview()

        self.view = self.viewFromXib()
        self.view!.frame = self.bounds
        self.view!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]

        if let subview = subview {
            let lConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 8)
            let rConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -8)
            let tConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 8)
            let bConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -8)
            self.view!.addSubview(subview)
            self.view!.addConstraints([lConstraint, rConstraint, tConstraint, bConstraint])
        }
        self.addSubview(self.view!)
    }

这种方法可以使用标签等进行推广,以添加多个子视图。