I haven't read anywhere yet if this is normal, but I can't get IBDesignable views to render in a standalone xib, such as a custom view or even a TableViewCell.
When I put them in a storyboard, they render perfectly fine. Here's an example for reference of my IBDesignable custom view:
@IBDesignable
class AvatarView: UIView, NibLoadable {
@IBOutlet public var contentView: UIView!
@IBOutlet public var backgroundView: CircleView!
@IBOutlet public var label: UILabel!
@IBOutlet public var imageView: UIImageView!
@IBInspectable var labelText: String = "" {
didSet {
self.label.text = labelText
}
}
@IBInspectable var image: UIImage? = nil {
didSet {
self.imageView.image = image
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupFromNib()
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupFromNib()
commonInit()
}
private func commonInit() {
clipsToBounds = true
layer.masksToBounds = true
self.backgroundColor = .clear
}
public func setUser(_ user: User) {
labelText = getInitialsForUser(user)
}
public func setImageUrl(_ urlString: String) {
self.imageView.kf.setImage(with: URL(string: urlString)!)
}
//MARK -- PRIVATE --
fileprivate func getInitialsForUser(_ user: User) -> String {
var name = ""
if let fullName = user.getFullName() {
name = fullName
}
return name.components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.first!)") + "\($1.first!)" }
}
}
Here is the NibLoadable class as well:
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
static var nibName: String {
return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
}
static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
One can use @IBDesignable
views inside a NIB/XIB. E.g.
One simply cannot access any project resources (NIBs, custom named colors, assets, etc.) programmatically from within an @IBDesignable
view. Designables rendered in Interface Builder do not have access to your bundle. Designables run in a stand-alone environment.
So, yes, you can use designables in NIBs, but just not the other way around.