我似乎无法让“titleText”IBInspectable 属性正常工作。我有一个带有 UILabel 的简单框架视图,我创建了一个 IBInspectable 变量“titleText”。我注意到可检查的“层”变量按预期工作,但不是我的自定义“titleText”,它应该使用这个框架更新主视图。
问题是:
Interface Builder 不更新titleLabel?(即在设计时)即我期望这应该,就像它适用于“层”项目一样。
在运行时,titleLabel 的值也没有达到我在 IB 中设置的值。请注意,当我运行时,我得到以下输出,即产生此输出的代码发现“self.titleLabel”实际上是 nil?
代码摘要
(b) gcCustomerView.swift
import UIKit
@IBDesignable
class gcCustomView: UIView {
@IBOutlet weak var titleLabel: UILabel!
@IBInspectable var titleText: String = "Default" {
didSet {
if self.titleLabel != nil {
self.titleLabel.text = titleText
} else {
NSLog("Could not set title text as label.text was nil : was trying to set to \(titleText)")
}
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commitInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commitInit()
}
// Private
func commitInit() {
if self.subviews.count == 0 {
print("Loading Nib")
//let bundle = Bundle(forClass: self.dynamicType)
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "gcCustomView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
}
}
}
(c) Main.storyboard 快照