如果这是正常的话,我还没看过任何地方,但是我无法获得IBDesignable视图以独立的Xib呈现,例如自定义视图,甚至是TableViewCell。
当我将它们放在情节提要中时,它们的渲染效果非常好。这是我的IBDesignable自定义视图的参考示例:
@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!)" }
}
}
这也是NibLoadable类:
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
}
}