一尘不染

在Swift中设置UITextField的最大字符长度

swift

我知道还有其他主题,但似乎无法找到实现方法。

我试图将UITextField限制为仅5个字符

最好是字母数字和-和。和_

我看过这段代码

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
                       replacementString string: String) -> Bool
{
    let maxLength = 4
    let currentString: NSString = textField.text
    let newString: NSString =
             currentString.stringByReplacingCharactersInRange(range, withString: string)
    return newString.length <= maxLength
}

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

    let length = count(textField.text.utf16) + count(string.utf16) - range.length
    return length <= 10 
}

我只是不知道如何实际实现它,或者我应该换成我的自定义UITextField换成哪个“ textfield”


阅读 827

收藏
2020-07-07

共1个答案

一尘不染

  1. 您的视图控制器应符合UITextFieldDelegate,如下所示:

    class MyViewController: UIViewController, UITextFieldDelegate {
    

    }

  2. 设置文本字段的委托: myTextField.delegate = self

  3. 在您的视图控制器中实现该方法: textField(_:shouldChangeCharactersInRange:replacementString:)

全部一起:

class MyViewController: UIViewController,UITextFieldDelegate  //set delegate to class

@IBOutlet var mytextField: UITextField             //  textfield variable

override func viewDidLoad() {
    super.viewDidLoad()
    mytextField.delegate = self                  //set delegate
}


func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
                       replacementString string: String) -> Bool
{
    let maxLength = 4
    let currentString: NSString = textField.text
    let newString: NSString =
             currentString.stringByReplacingCharactersInRange(range, withString: string)
    return newString.length <= maxLength
}

对于Swift 4

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let maxLength = 1
    let currentString: NSString = textField.text! as NSString
    let newString: NSString =
        currentString.replacingCharacters(in: range, with: string) as NSString
    return newString.length <= maxLength
}

只允许在给定的文本字段中输入一组指定的字符

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

  if mytextField == numberField {
    if count(string) > 0 {
      let disallowedCharacterSet = NSCharacterSet(charactersInString: "0123456789.-").invertedSet
      let replacementStringIsLegal = string.rangeOfCharacterFromSet(disallowedCharacterSet) == nil
      result = replacementStringIsLegal
    }
  }

  return result
}

如何对仅包含最大长度的数字输入的iOS文本字段进行编程

2020-07-07