具有XIB文件的自定义UIView
如上图所示,您可能遇到了一些示例。 我现在将向您展示如何实现这一目标。 这种方法非常易于使用,可以使您的代码保持整洁。
创建一个超级类
我们将创建一个名为NibView的超类,该类将处理有关XIB文件合并的所有内容。 创建超类的力量在于可重用性。 您可以使每个UIView从其父类继承。
import UIKit
class NibView: UIView { var view: UIView!
override init(frame: CGRect) { super.init(frame: frame) // Setup view from .xib file xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Setup view from .xib file xibSetup() } }
private extension NibView { func xibSetup() { backgroundColor = UIColor.clear view = loadNib() // use bounds not frame or it'll be offset view.frame = bounds // Adding custom subview on top of our view addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[childView]|", options: [], metrics: nil, views: ["childView": view])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[childView]|", options: [], metrics: nil, views: ["childView": view])) } }
魔术发生在xibSetup()函数内部。 我们通过使用NSLayoutConstraints来确保UIView与其父视图一样大。
创建UIView扩展
为了初始化自定义XIB文件,我创建了一个名为loadNib()的UIView扩展。
import UIKit
extension UIView {
/** Loads instance from nib with the same name. */ func loadNib() -> UIView { let bundle = Bundle(for: type(of: self)) let nibName = type(of: self).description().components(separatedBy: ".").last! let nib = UINib(nibName: nibName, bundle: bundle) return nib.instantiate(withOwner: self, options: nil).first as! UIView } }
/** Loads instance from nib with the same name. */ func loadNib() -> UIView { let bundle = Bundle(for: type(of: self)) let nibName = type(of: self).description().components(separatedBy: ".").last! let nib = UINib(nibName: nibName, bundle: bundle) return nib.instantiate(withOwner: self, options: nil).first as! UIView } }
在自定义UIView类中继承NibView
最后一步是创建一个自定义UIView和一个将从NibView超类继承的XIB文件。
class CustomView: NibView {
}
然后,导航到您的XIB文件,从左侧边栏中选择“文件的所有者”,并将自定义UIView添加为其自定义类。
现在,转到您的UIViewController,添加一个UIView组件,然后将您的UIView添加为自定义类。 为了使这种方法起作用,请记住将您的XIB文件命名为UIView类。
当您需要直接从UIViewController而不是其XIB文件初始化UIView时,使用此方法。 我正在使用上面提到的相同的UIView扩展。
let customView = CustomView().loadNib() as! CustomView customView.frame = /* add your frame */ view.addSubview(customView)
这就是初始化UIView和XIB文件所需的全部。