保护文本.echosbullets不适用于密码字段

时间:2017-10-22 23:31:04

标签: swift macos nstextfield

以下是我所拥有的:

@IBOutlet weak var password: NSSecureTextField! 
@IBOutlet weak var shwpswd: NSButton! //Checkbox
@IBOutlet weak var pswdcell: NSSecureTextFieldCell! //Cell


@IBAction func shwpswd(_ sender: Any) {
    if(shwpswd.state == 1) {
        pswdcell.echosBullets = false // Turn the Secure text into regular text
    }
    else if(shwpswd.state == 0) {
        pswdcell.echosBullets = true // Secure text
    }
}

除了密码字段中的文字不会改变回显子弹之间的状态并回显真实文本外,一切似乎都运行正常。一切都正确地链接在一起--Cell在文本字段内,密码按钮在视图中,插座工作。我想知道这是否是另一个" Swift on mac< Swift on iOS case"。

编辑:这是最终的解决方案,任何人都应该关注它:

@IBOutlet weak var shwpswd: NSButton! //Checkbox
@IBOutlet weak var visPswd: NSTextfield! //hidden regular box to show chars
@IBOutlet weak var password: NSSecureTextField!    //visible initial secure box
@IBAction func shwpswd(_ sender: Any) {
    if(shwpswd.state == 1) {
        self.visPswd.stringValue = self.password.stringValue //Sync both the text fields
        self.password.isHidden = true //hide the secure field
        self.visPswd.isHidden = false //show the real character echo field
    }
    else if(shwpswd.state == 0) {
        self.password.stringValue = self.visPswd.stringValue //Sync the two
        self.password.isHidden = false // Inverse of above
        self.visPswd.isHidden = true
    }
}

请注意,文本字段passwordvisPswd在视图中的大小和位置相同 - 其中一个始终隐藏,以避免重叠。当用户在passwordvisPswd字段中输入值时,当复选框状态发生变化时,它会与其他字段同步。

1 个答案:

答案 0 :(得分:1)

您可以在安全字段的顶部添加第二个文本字段。在复选框中添加IBAction以切换字段isHidden属性并复制另一个textField stringValue并使其成为第一个响应者。您的实现应该如下所示:

import Cocoa

class ViewController: NSViewController {
    @IBOutlet weak var password: NSSecureTextField!
    @IBOutlet weak var showPassword: NSTextField!
    @IBOutlet weak var shwpswd: NSButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        shwpswd.state = .off
        showPassword.isHidden = true
    }
    override func viewDidAppear() {
        super.viewDidAppear()
        password.window?.makeFirstResponder(password)
    }
    @IBAction func showHidePassword(_ sender: NSButton) {
        showPassword.isHidden = !showPassword.isHidden
        password.isHidden = !password.isHidden
        if !showPassword.isHidden {
            showPassword.stringValue = password.stringValue
            showPassword.becomeFirstResponder()
        } else {
            password.stringValue = showPassword.stringValue
            password.becomeFirstResponder()
        }
    }
}

show/hide password sample