mra214 mra214 - 7 months ago 41
Swift Question

How to hide UITextField text with subview?

I need to hide text property of the UITextField with subview.
It seems quite straightforward, but unfortunately it doesn't work.
What do I do wrong?

Here's the code:

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)
}

Answer
    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 ...

OR you simply change the z order of lable than also it is working.

    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)