gpt4 book ai didi

ios - 如何在 Swift 3 iOS 中限制 TextField 的双/单空格

转载 作者:搜寻专家 更新时间:2023-11-01 07:10:02 24 4
gpt4 key购买 nike

我的 iOS 应用程序中有登录页面,它是用 Swift 语言开发的。在第一个字母中不应使用单/双空格,并且在用户输入文本后应允许单空格,不允许双空格并且需要设置文本长度限制。

我想限制用户在开始输入文本时点击单/双空格,并且在文本字段中输入第一个字母后需要允许单空格

我可以做单人/双人中的任何一个,但没有按照我的要求工作。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//for double space restrict
if (range.location > 0 && (textField.text?.characters.count)! > 0) {
//Manually replace the space with your own space, programmatically
//Make sure you update the text caret to reflect the programmatic change to the text view
//Tell Cocoa not to insert its space, because you've just inserted your own
return false
}else {
if textField.tag == 1 || textField.tag == 2 { //restrict text length
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLengthForTextField
}
}

return true
}

谁能给点建议。谢谢

最佳答案

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let rawString = string
let range = rawString.rangeOfCharacter(from: .whitespaces)
if ((textField.text?.characters.count)! == 0 && range != nil)
|| ((textField.text?.characters.count)! > 0 && textField.text?.characters.last == " " && range != nil) {
return false
}
return true
}

关于ios - 如何在 Swift 3 iOS 中限制 TextField 的双/单空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45543141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com