gpt4 book ai didi

ios - 限制文本字段中的字符和字符长度(_ :shouldChangeCharactersInRange:replacementString:)

转载 作者:行者123 更新时间:2023-11-28 09:36:48 24 4
gpt4 key购买 nike

我的应用程序中有一个用户名文本字段,我想将其限制为 24 个字符并且不允许使用“|”用户名中的管道。

我可以使用下面的代码单独执行这些操作,但是我无法将它们组合到 textField(_:shouldChangeCharactersInRange:replacementString:) 中。

此代码成功禁止“|”在用户名字段中。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

if textField === usernameField {
// Create an `NSCharacterSet` set
let set = NSCharacterSet(charactersInString:"|")

// At every character in this "set" contained in the string,
// split the string up into components which exclude the characters
// in this inverse set
let components = string.componentsSeparatedByCharactersInSet(set)

// Rejoin these components
let filtered = components.joinWithSeparator("")

// If the original string is equal to the filtered string, i.e. if no
// characters were present to be eliminated, the input is valid
// and the statement returns true; else it returns false
return string == filtered
} else {
return true
}
}

此代码成功地将用户名字段限制为 24 个字符。

  func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Added to limit title to <= 40 characters
guard let text = meetupTitleTextField.text else { return true }

let newLength = text.utf16.count + string.utf16.count - range.length
return newLength <= 48 // Bool
}

如果有任何关于如何将它们组合到 textField(_:shouldChangeCharactersInRange:replacementString:) 中的建议,我将不胜感激

最佳答案

试试这个:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == usernameField, let text = textField.text {
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 48 && !string.containsString("|")
}

return true
}

关于ios - 限制文本字段中的字符和字符长度(_ :shouldChangeCharactersInRange:replacementString:),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37366639/

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