我想创建一个自定义的TextField类,在这个类中,我可以在storyboard中从IBInspectable属性中添加标签(就像下面这个)。
焦点状态
默认状态
我能够在自定义类中实现TextField的聚焦和不聚焦状态,但无法解决如何从自定义类中将UILabel放在TextField上方。
以下是我目前所尝试的方法
@IBDesignable class CustomTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
setupTextField()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupTextField()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.setupTextField()
}
private func setupTextField() {
applyDefaultStyle()
addTarget(self, action: #selector(applyActiveStyles), for: UIControl.Event.editingDidBegin)
addTarget(self, action: #selector(applyDefaultStyles), for: UIControl.Event.editingDidEnd)
let label = UILabel()
label.text = "First name"
addSubview(label)
label.bottomAnchor.constraint(equalTo: topAnchor, constant: -10).isActive = true
label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0).isActive = true
}
.
.
.
}
但是标签是不可见的。
在标签的左边和垂直中心添加约束条件,不要忘记设置 translatesAutoresizingMaskIntoConstraints
到 false
private func setupTextField() {
applyDefaultStyle()
addTarget(self, action: #selector(applyActiveStyles), for: UIControl.Event.editingDidBegin)
addTarget(self, action: #selector(applyDefaultStyles), for: UIControl.Event.editingDidEnd)
let label = UILabel()
label.text = "First name"
addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true
label.bottomAnchor.constraint(equalTo: topAnchor, constant: -2).isActive = true
}