如何在 Swift 中切换 UITextField 安全文本条目(隐藏密码) ?

我目前有一个 UITextfield与眼睛图标在其中,当按下应切换安全文本条目和关闭。

secure text entry

我知道你可以在属性检查器中选中“安全文本输入”框,但是如何做到这一点,以便它在按下图标时能够切换?

104254 次浏览

试试这句话:

@IBAction func btnClick(sender: AnyObject) {
let btn : UIButton = sender as! UIButton
if btn.tag == 0{
btn.tag = 1
textFieldSecure.secureTextEntry = NO
}
else{
btn.tag = 0
textFieldSecure.secureTextEntry = NO;
}
}

使用带有眼睛图像的按钮
并使用 buttonHandler 方法
为值为1的按钮设置 Tag

-(IBAction) buttonHandlerSecureText:(UIButton *)sender{
if(sender.tag ==1){
[self.textField setSecureTextEntry:NO];
sender.tag = 2;
}
else{
[self.textField setSecureTextEntry:YES];
sender.tag = 1;
}
}
@IBAction func eye_toggle_clicked(sender: AnyObject)
{
if toggleBtn.tag == 0
{
passwordTxt.secureTextEntry=true
toggleBtn.tag=1
}
else
{
passwordTxt.secureTextEntry=false
toggleBtn.tag=0
}
}

赋值值从 YES/NO变为 true/false布尔值。

password.secureTextEntry = true //Visible
password.secureTextEntry = false //InVisible

你可以试试这个代码. 。 我觉得很有帮助。

用这个密码,

IconClick 是 bool 变量,或者您需要其他条件检查它,

var iconClick = true

眼睛动作法:

@IBAction func iconAction(sender: AnyObject) {
if iconClick {
passwordTF.secureTextEntry = false
} else {
passwordTF.secureTextEntry = true
}
iconClick = !iconClick
}

希望能有所帮助

正如其他人所指出的,这个属性是 secureTextEntry,但是在 UITextField文档中找不到这个属性,因为它实际上是由 UITextField通过 UITextInputTraits协议 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextInputTraits_Protocol/#//apple_ref/occ/intfp/UITextInputTraits/secureTextEntry继承的

你可以在每次点击按钮时简单地切换这个值:

@IBAction func togglePasswordSecurity(sender: UIButton) {
self.passwordField.secureTextEntry = !self.passwordField.secureTextEntry
}

这是你的答案,不需要采取任何 bool var:

@IBAction func showHideAction(sender: AnyObject) {


if tfPassword.secureTextEntry{
tfPassword.secureTextEntry = false


}else{
tfPassword.secureTextEntry = true;
}
}

为什么要使用额外的 var。在 眼睛的动作方法中按下面的按钮就可以了吗

password.secureTextEntry = !password.secureTextEntry

更新

Swift 4.2 (根据@ROC 评论)

password.isSecureTextEntry.toggle()

目标 c

在视图中为右键设置图像

[RightButton setImage:[UIImage imageNamed:@"iconEyesOpen"] forState:UIControlStateNormal];


[RightButton setImage:[UIImage imageNamed:@"iconEyesClose"] forState:UIControlStateSelected];

然后为右键设置操作方法

-(IBAction)RightButton:(id)sender
{


if (_rightButton.selected)
{


_rightButton.selected = NO;


_passwordText.secureTextEntry = YES;




if (_passwordText.isFirstResponder) {
[_passwordText resignFirstResponder];
[_passwordText becomeFirstResponder];
}
}
else
{


_rightButton.selected = YES;


_passwordText.secureTextEntry = NO;


if (_passwordText.isFirstResponder) {
[_passwordText resignFirstResponder];
[_passwordText becomeFirstResponder];
}


}
}

使用 UITextFiledright 视图显示切换按钮

 var rightButton  = UIButton(type: .custom)
rightButton.frame = CGRect(x:0, y:0, width:30, height:30)
yourtextfield.rightViewMode = .always
yourtextfield.rightView = rightButton

Swift 3

passwordTF.isSecureTextEntry = true
passwordTF.isSecureTextEntry = false

Swift 3

//    MARK: Btn EyeAction
@IBAction func btnEyeAction(_ sender: Any) {


if(iconClick == true) {
txtPassword.isSecureTextEntry = false
iconClick = false
} else {
txtPassword.isSecureTextEntry = true
iconClick = true
}
}

首先您需要设置图像(可见或隐藏)的眼睛按钮为不同的状态(选择或正常)

而不是连接 IBAction 并编写如下代码

@IBAction func btnPasswordVisiblityClicked(_ sender: Any) {
(sender as! UIButton).isSelected = !(sender as! UIButton).isSelected
if (sender as! UIButton).isSelected {
txtfPassword.isSecureTextEntry = false
} else {
txtfPassword.isSecureTextEntry = true
}
}

this is example of "How to set image for different state of button"

对于 Xamarin 人来说:

SecureTextEntry = passwordField. SecureTextEntry? passwordField. SecureTextEntry = false: passwordField. SecureTextEntry = true;

这样做的一个意想不到的副作用是,如果用户切换到不安全,然后 回来切换到安全,那么如果用户继续键入,现有的文本将被清除。除非我们重置选定的文本范围,否则光标也可能最终出现在错误的位置。

下面是一个处理这些情况的实现(Swift 4)

extension UITextField {
func togglePasswordVisibility() {
isSecureTextEntry = !isSecureTextEntry


if let existingText = text, isSecureTextEntry {
/* When toggling to secure text, all text will be purged if the user
continues typing unless we intervene. This is prevented by first
deleting the existing text and then recovering the original text. */
deleteBackward()


if let textRange = textRange(from: beginningOfDocument, to: endOfDocument) {
replace(textRange, withText: existingText)
}
}


/* Reset the selected text range since the cursor can end up in the wrong
position after a toggle because the text might vary in width */
if let existingSelectedTextRange = selectedTextRange {
selectedTextRange = nil
selectedTextRange = existingSelectedTextRange
}
}
}

这个代码片段使用了 replace(_:withText:)函数,因为它触发了 .editingChanged事件,这在我的应用程序中很有用。只要设置 text = existingText就可以了。

尝试使用 Swift 4中的代码,尝试在控制器中创建可重用的代码。我已经为故事板中的按钮设置了不同的图像,如链接 https://stackoverflow.com/a/47669422/8334818所示

@IBAction func clickedShowPassword(_ sender: UIButton) {
var textField :UITextField? = nil
print("btn ",sender.isSelected.description)
switch sender {
case encryptOldPswdBtn:
encryptOldPswdBtn.isSelected = !encryptOldPswdBtn.isSelected
textField = oldPasswordTextField


default:
break
}


print("text ",textField?.isSecureTextEntry.description)
textField?.isSecureTextEntry = !(textField?.isSecureTextEntry ?? false)


}

迅捷4 解决方案

对于简单的 toggle isSecureTextEntry 属性,不需要额外的 if 语句

func togglePasswordVisibility() {
password.isSecureTextEntry = !password.isSecureTextEntry
}

但是有一个问题,当您切换 isSecureTextEntry UITextField 不重新计算文本宽度,我们有额外的空间到右侧的文本。为了避免这种情况,您应该以这种方式替换文本

func togglePasswordVisibility() {
password.isSecureTextEntry = !password.isSecureTextEntry
if let textRange = password.textRange(from: password.beginningOfDocument, to: password.endOfDocument) {
password.replace(textRange, withText: password.text!)
}
}

更新

Swift 4.2

而不是

password.isSecureTextEntry = !password.isSecureTextEntry

你能做到的

password.isSecureTextEntry.toggle()

在 Swift 4里

 var iconClick : Bool!


override func viewDidLoad() {
super.viewDidLoad()
iconClick = true
}




@IBAction func showHideAction(_ sender: Any)
{
let userPassword = userPasswordTextFiled.text!;


if(iconClick == true) {
userPasswordTextFiled.isSecureTextEntry = false
iconClick = false
} else {
userPasswordTextFiled.isSecureTextEntry = true
iconClick = true
}


}

如果您需要在多个地方具有类似功能的 TextField,最好子类化 UITextField,如下例所示-

import UIKit


class UIShowHideTextField: UITextField {


let rightButton  = UIButton(type: .custom)


required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}


required override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}


func commonInit() {
rightButton.setImage(UIImage(named: "password_show") , for: .normal)
rightButton.addTarget(self, action: #selector(toggleShowHide), for: .touchUpInside)
rightButton.frame = CGRect(x:0, y:0, width:30, height:30)


rightViewMode = .always
rightView = rightButton
isSecureTextEntry = true
}


@objc
func toggleShowHide(button: UIButton) {
toggle()
}


func toggle() {
isSecureTextEntry = !isSecureTextEntry
if isSecureTextEntry {
rightButton.setImage(UIImage(named: "password_show") , for: .normal)
} else {
rightButton.setImage(UIImage(named: "password_hide") , for: .normal)
}
}


}

之后您可以在任何 ViewController 中使用它,

class ViewController: UIViewController {


@IBOutlet var textField: UIShowHideTextField!


override func viewDidLoad() {
super.viewDidLoad()
textField.becomeFirstResponder()
}


}
@objc func togglePasscode(){


switch textfield.isSecureTextEntry{
case true:
textfield.isSecureTextEntry = false


case false:
textfield.isSecureTextEntry = true
}
}

下面是一个使用 Switch 语句的简单且更易读的解决方案。

最短的!

我认为这是最短的安全进入的解决方案,以及更新图片的按钮。

@IBAction func toggleSecureEntry(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
textfieldPassword.isSecureTextEntry = !sender.isSelected
}

根据选择/默认状态分配按钮的显示/隐藏图片,不需要创建任何变量或出口。

希望这是一个更简单的解决方案,而不是在全局范围内创建 BOOL 对象。

@IBAction func passwordToggleButton(sender: UIButton) {
let isSecureTextEntry = passwordTextField.isSecureTextEntry
passwordTextField.isSecureTextEntry = isSecureTextEntry ? false : true
if isSecureTextEntry {
visibilityButton.setImage(UIImage(named: "visibility"), for: .normal)
} else {
visibilityButton.setImage(UIImage(named: "visibility_off"), for: .normal)
}
}

我写了相同的扩展。提供密码切换。

iOS password toggle eye icons

  1. 在“资产”中,首先添加要切换的图像。

  2. 为 UITextField 添加以下扩展。

    extension UITextField {
    fileprivate func setPasswordToggleImage(_ button: UIButton) {
    if(isSecureTextEntry){
    button.setImage(UIImage(named: "ic_password_visible"), for: .normal)
    }else{
    button.setImage(UIImage(named: "ic_password_invisible"), for: .normal)
    
    
    }
    }
    
    
    func enablePasswordToggle(){
    let button = UIButton(type: .custom)
    setPasswordToggleImage(button)
    button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0)
    button.frame = CGRect(x: CGFloat(self.frame.size.width - 25), y: CGFloat(5), width: CGFloat(25), height: CGFloat(25))
    button.addTarget(self, action: #selector(self.togglePasswordView), for: .touchUpInside)
    self.rightView = button
    self.rightViewMode = .always
    }
    @IBAction func togglePasswordView(_ sender: Any) {
    self.isSecureTextEntry = !self.isSecureTextEntry
    setPasswordToggleImage(sender as! UIButton)
    }
    }
    
  3. UITextField插座的呼叫分机

     override func viewDidLoad() {
    super.viewDidLoad()
    txtPassword.enablePasswordToggle()
    txtConfirmPassword.enablePasswordToggle()
    }
    

只在代码中添加这一行,将 TextField 名称替换为“ TextField”完成: 您需要更改 isSecureTextEntry 属性以更改密码类型 textFiled 的 true,如... ..。

textField.isSecureTextEntry = true
 sender.isSelected = !sender.isSelected
if(sender.isSelected == true) {
RegPasswordField.isSecureTextEntry = false
sender.setBackgroundImage(UIImage(systemName: "eye.fill"), for: .normal)
} else {
RegPasswordField.isSecureTextEntry = true
sender.setBackgroundImage(UIImage(systemName: "eye"), for: .normal)
}

这在 Swift 5.0上对我很管用

@IBAction func changePasswordVisibility(_ sender: UIButton) {
passwordField.isSecureTextEntry.toggle()
if passwordField.isSecureTextEntry {
if let image = UIImage(systemName: "eye.fill") {
sender.setImage(image, for: .normal)
}
} else {
if let image = UIImage(systemName: "eye.slash.fill") {
sender.setImage(image, for: .normal)
}
}
}

按钮属性:

enter image description here

结果:

enter image description here enter image description here

请用这个

var btnClick = true


if(btnClick == true) {
passwordTextField.isSecureTextEntry = false
} else {
passwordTextField.isSecureTextEntry = true
}
        

btnClick = !btnClick


}
var viewingPassword = true


@IBAction func btnEyeAction(_ sender: Any) {
passwordTF.isSecureTextEntry = viewingPassword ? false : true
viewingPassword.toggle()
}