我尝试在UITextField初始化后设置rightView
,但它得到nil
。这是我的班级:
class MyTextField: UITextField, UIGestureRecognizerDelegate {
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
public override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
public convenience init() {
self.init(frame: .zero)
}
open private(set) var errorUIImageView = UIImageView(image: (resourceName: "ic_error_red"))
open func prepare() {
print("prepare")
let tap = UITapGestureRecognizer(target: self, action: Selector(("handleTap:")))
tap.numberOfTapsRequired = 1
tap.delegate = self
errorUIImageView.isUserInteractionEnabled = true
errorUIImageView.addGestureRecognizer(tap)
self.rightView = errorUIImageView // setting the rightView here
}
@IBInspectable
open var detail: String? {
get {
return detailLabel.text
}
set(value) {
detailLabel.text = value
if let v: String = value {
self.rightViewMode = .always
if self.rightView == nil {
print("nil") // this line is reached!
}
}
else {
self.rightViewMode = .never;
}
}
}
@IBInspectable
open var detailColor = UIColor.red {
didSet {
if let v: String = detailLabel.text {
detailLabel.attributedText = NSAttributedString(string: v, attributes: [NSForegroundColorAttributeName: detailColor])
}
}
}
@IBInspectable
open private(set) lazy var detailLabel = UILabel(frame: .zero)
func handleTap(sender: UITapGestureRecognizer) {
print("tapped")
}
}
大多数代码都来自Material