storyboard中能够插入xib定义的view,并能够预览,xib中插入xib使用方法和storyboard是一样的方法.(Swift3.0版)
-
先新建好自定义的xib和对应的类,注意类名必须和xib中绑定的类名一致,否则无法在类中关联xib中的组件(进行连线)
自定义类的代码如下:
import UIKit
@IBDesignable
class CustomView: UIView {
@IBOutlet weak var label: UILabel!
@IBAction func onTouchUp(_ sender: UIButton) {
onButtonRun?()
}
@IBInspectable
var name:String?{
get{
return label.text
}
set{
label.text = newValue
}
}
var onButtonRun:(()->Void)?
//初始化时将xib中的view添加进来
var contentView:UIView!
override init(frame: CGRect) {
super.init(frame: frame)
contentView = loadViewFromNib()
addSubview(contentView)
addConstraints()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
contentView = loadViewFromNib()
addSubview(contentView)
addConstraints()
}
//加载xib
func loadViewFromNib() -> UIView {
let className = type(of: self)
let bundle = Bundle(for: className)
let name = NSStringFromClass(className).components(separatedBy: ".").last
let nib = UINib(nibName: name!, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
//设置好约束
func addConstraints() {
contentView.translatesAutoresizingMaskIntoConstraints = false
var constraint = NSLayoutConstraint(item: contentView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
addConstraint(constraint)
constraint = NSLayoutConstraint(item: contentView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
addConstraint(constraint)
constraint = NSLayoutConstraint(item: contentView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
addConstraint(constraint)
constraint = NSLayoutConstraint(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
addConstraint(constraint)
}
}
2.在storyboard中拖入一个View组件,然后将class设置为我们自定义的类名"CustomView"
3.这是我在自定义类中增加的可以编辑的属性,修改也能够实时预览它
源码实现:https://github.com/ghyh22/StoryboardInsertXibView
参考:http://swiftdeveloperblog.com/creating-custom-user-interface-files-with-xib-in-xcode-6-and-swift/