根据 IOS swift 中的复选框状态禁用/启用返回键



>我有一个带有文本字段和两个复选框的屏幕。当用户点击文本字段时,将显示键盘。我想根据以下条件启用/禁用软键盘上的返回键。

当文本字段不为空且两个复选框均处于选中状态时启用。 当文本字段为空或未选中任一复选框时禁用。

有可能做到这一点吗?

创建用于存储复选框按钮的当前状态的按钮数组并连接复选框按钮此数组,它将用于获取按钮的当前状态

var getSelectedState: [UIButton] = []

使用"第一"获取复选框按钮当前状态(其中:(

返回满足给定谓词的序列的第一个元素。

var handleButtonState : Bool{
var setState = false
if let getNotSelectedState = getSelectedState.first(where: { $0.isSelected == false }) {
print("get the non selectedState of button (getNotSelectedState)")
setState = true
}
return setState
}

最后,您可以使用 UI文本字段委托来启用/禁用返回键,使用启用返回键自动

一个布尔值,指示在用户输入文本时是否自动启用 Return 键。

// MARK: - Textfield delegates
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let currentText = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) else { return true }
textField.enablesReturnKeyAutomatically = !currentText.isEmpty && !handleButtonState ? true :  false        
return true 
}

这里的用户名和密码是两个UITextField,右视图是复选框(Uiview包括wrror按钮或图像或复选框(

self.textField.delegate = self;
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//let maxLength = 4
let currentString: NSString = textField.text! as NSString
let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString
if newString.length == 1 && textField == self.username {
self.username.rightView = nil
}
if newString.length == 1 && textField == self.password {
self.password.rightView = nil
}
return true//newString.length <= maxLength
}

我在我的项目中尝试过,希望它对您有用...:)

启用或禁用返回按钮只会在textField的文本上自动发生,无论它是否为空,为了进行更多自定义,我们可以使用textFieldShouldReturn方法。

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let txt = textField.text,
isBothCheckBoxChecked(),
!txt.isEmpty{
return true
}
return false
}

func isBothCheckBoxChecked() -> Bool {
var checked = false
// write condition here
return checked
}

最新更新