在自定义类的UITextField上面添加一个标签。

问题描述 投票:-1回答:2

我想创建一个自定义的TextField类,在这个类中,我可以在storyboard中从IBInspectable属性中添加标签(就像下面这个)。

焦点状态

enter image description here

默认状态

enter image description here

我能够在自定义类中实现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
    }

    .
    .
    .

}

但是标签是不可见的。

ios swift uitextfield
2个回答
1
投票

在标签的左边和垂直中心添加约束条件,不要忘记设置 translatesAutoresizingMaskIntoConstraintsfalse

 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
  }

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.