如何用子视图隐藏 UITextField 文本?

How to hide UITextField text with subview?

我需要用子视图隐藏 UITextField 的文本 属性。 这看起来很简单,但不幸的是它不起作用。 我做错了什么?

代码如下:

override func viewDidLoad() {
    super.viewDidLoad()

    let txtField = UITextField()
    txtField.frame = CGRect(x: 10, y: 50, width: 300, height: 30)
    txtField.text = "This text is hidden under UILabel"
    txtField.backgroundColor = UIColor.blueColor()
    view.addSubview(txtField)

    let label = UILabel()
    label.frame = CGRect(x: 0, y: 0, width: 300, height: 30)
    label.backgroundColor = UIColor.redColor()
    label.textColor = UIColor.whiteColor()
    label.text = "This text should appear on top"

    txtField.addSubview(label)
    txtField.bringSubviewToFront(label)
}

看来不可能 addSubviewUITextField。相反,可以将其添加到文本字段上的 view

    let txtField = UITextField()
    txtField.frame = CGRect(x: 10, y: 50, width: 300, height: 30)
    txtField.text = "This text is hidden under UILabel"
    view.addSubview(txtField)

    let label = UILabel()
       let label = UILabel()
   // label.frame = CGRect(x: 0, y: 0, width: 300, height: 30)
    label.frame = txtField.frame
    label.backgroundColor = UIColor.redColor()
    label.textColor = UIColor.whiteColor()
    label.text = "This text should appear on top"


    label.backgroundColor = UIColor.redColor()
    label.textColor = UIColor.whiteColor()
    label.text = "This text should appear on top"

    view.addSubview(label) // add label on view with same position ...

或者您只需更改标签的 z 顺序即可。

    let txtField = UITextField()
    txtField.frame = CGRect(x: 10, y: 50, width: 300, height: 30)
    txtField.backgroundColor = UIColor.yellowColor()
    txtField.text = "This text is hidden under UILabel"
    view.addSubview(txtField)

    let label = UILabel()
    label.frame = CGRect(x: 0, y:0, width: 300, height: 30)
    label.backgroundColor = UIColor.redColor()
    label.textColor = UIColor.whiteColor()
    label.text = "This Label should appear on top"
    label.layer.zPosition=1
    txtField.addSubview(label)

这对我有用:

override func viewWillAppear(animated: Bool) {
        let sampleTextField = UITextField()
sampleTextField.frame = CGRect(x: 10, y: 50, width: 300, height: 100)
sampleTextField.text = "This text is hidden under UIsampleBackgroundLabel"
sampleTextField.textColor =  UIColor.blackColor()
sampleTextField.backgroundColor = UIColor.whiteColor()
view.addSubview(sampleTextField)

let sampleBackgroundLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 30))
sampleBackgroundLabel.textColor = UIColor.whiteColor()
sampleBackgroundLabel.text = "This text should appear on top"


sampleTextField.addSubview(sampleBackgroundLabel)
sampleTextField.sendSubviewToBack(sampleBackgroundLabel)


}

使用循环检查。

if(condition == true)
        {
            sampleBackgroundLabel.textColor = UIColor.whiteColor()
        }
        else
        {
            sampleBackgroundLabel.textColor = UIColor.blueColor()

        }