How to render xib on Storyboard?

How to render xib custom view on Storyboard using IBDesignable in iOS

When you create the custom view with xib and then set the custom view on Storyboard but if It has not appeared. How can you solve the rendering issue?

I stuck in similar issues on Xcode 11.

xcode 11 said -> Failed to render and update auto layout the agent threw an exception

Here is my solution and I hope it helps you!

customView.png
import UIKit
@IBDesignable
class XibView: UIView {
let className = String(describing: XibView.self)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupNib()
}
private func setupNib() {
guard let nib = loadNib() else { return }
nib.translatesAutoresizingMaskIntoConstraints = false
addSubview(nib)
NSLayoutConstraint.activate([
nib.leadingAnchor.constraint(equalTo: self.leadingAnchor),
nib.trailingAnchor.constraint(equalTo: self.trailingAnchor),
nib.topAnchor.constraint(equalTo: self.topAnchor),
nib.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
func loadNib() -> UIView? {
let bundle = Bundle(for: Self.self)
return bundle.loadNibNamed(String(describing: Self.self), owner: self, options: nil)?.first as? UIView
}
}
image-asset.png


Discover more from Shawn

Subscribe now to keep reading and get access to the full archive.

Continue reading