我试图在iOS上创建一个基于组件的系统,我想做以下工作:
这个是可能的吗?
现在,对于所有IBDesignable组件,我使用以下超类从xibs加载它们的视图:
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创建占位符?
发布于 2017-12-05 00:41:12
视图最初包含子视图,因此将容器视图作为子视图添加到任何需要子组件的组件中。
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!)
}这种方法可以推广到标签等,以添加多个子视图。
https://stackoverflow.com/questions/47552442
复制相似问题