我尝试用Nib文件实现Custom Loader View。但我得到一个错误 在
的loadViewFromNib()
中
return nib.instantiate(withOwner: self, options: nil).first as? UIView.
线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x7ffee6f3df98)
open class LoaderView: UIView {
@IBOutlet var loaderImage: UIImageView!
@IBOutlet var contentView: UIView!
func xibSetup() {
contentView = loadViewFromNib()
contentView.frame = bounds
contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(contentView)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "LoaderView", bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}
我在viewDidLoad()
中的VC中将此加载程序称为
let loader = LoaderView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
view.addSubview(loader)
答案 0 :(得分:3)
您的代码很好,没有递归
请确保您拥有
1)仔细检查您的IBOUtlet连接
2)在文件所有者
中添加了您的课程我已经创建了与您的代码相同的
class CustomView: UIView {
let nibName = "CustomView"
@IBOutlet var view : UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetUp()
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetUp()
}
func xibSetUp() {
view = loadViewFromNib()
view.frame = self.bounds
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CustomView", bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as! UIView
}
}
看一下输出
答案 1 :(得分:2)
您有递归
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
您在loadViewFromNib()
中呼叫xibSetup()
,它呼叫UINib(nibName: "LoaderView", bundle: bundle)
,即呼叫required public init?(coder aDecoder: NSCoder)