ios - 如何用 subview 隐藏 UITextField 文本?

标签 ios swift uitextfield uilabel

我需要用 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)
}

最佳答案

    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)

关于ios - 如何用 subview 隐藏 UITextField 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36718585/

相关文章:

ios - 从 iOS 中 NSDictionary 内的字典中检索值

ios - 在没有互联网或使用库的情况下配置 IQKeyboardManager?

ios - AVAudioPlayer播放一个数据(一次)然后重复播放另一个数据(多次)

swift - 在我的 Swift 项目中加载本地 .scpt 文件会导致错误

ios - 快速更改另一个 View Controller 中的 UITextfield 子类值

ios - Sprite 套件与子 Sprite 的碰撞检测

ios - 从另一个图层中减去图层,混合?

ios - 带有 TableView 和手势识别器问题的 Swift/UIView

objective-c - 如何制作字幕 UILabel/UITextField/NSTextField

iphone - 如何使用 NSNumberFormatter 在 UITextField 中打印货币