I try to implement Custom Loader View with Nib file. But I get an error
in loadViewFromNib()
at
return nib.instantiate(withOwner: self, options: nil).first as? UIView.
Thread 1: EXC_BAD_ACCESS (code=2, address=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
}
}
I call this loader in VC in viewDidLoad()
as
let loader = LoaderView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
view.addSubview(loader)
Your code is fine there is no recursion
Please make sure you have
1) Double check your IBOUtlet connection
2) Added Your class in File's Owner
I have created This same as your code
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
}
}
Have look at output