简体   繁体   中英

How to limit length of input of Textfield - Swift 2

This code works perfectly, and I can't key in anything other than integers, even when I try to paste it in.

I'd like to add one more refinement, which is to limit the length of the input. Here's my code:

func initializeTextFields()
{
APTeams.delegate = self
APTeams.keyboardType = UIKeyboardType.NumberPad

APRounds.delegate = self
APRounds.keyboardType = UIKeyboardType.NumberPad

APBreakers.delegate = self
APBreakers.keyboardType = UIKeyboardType.NumberPad

}

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

// Find out what the text field will be after adding the current edit
let text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

if  text == "" {
    return true
}

if let _ = Int(text) {
    return true
}

else {
    return false
}

}

What do I have to add to it to achieve this? The maximum input length for all the TextFields should be <= 4.

BTW, all code is in Swift 2. From problems I faced when trying to implement answers to questions I've asked before, I gather that some of the methods are different.

count(textField.text) is deprecated in SWIFT 2.0

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

        if let textField = textField as? UITextField {

            if (range.length + range.location > textField.text!.characters.count) {
                return false;
            }

            let newLength = textField.text!.characters.count + string.characters.count - range.length;
            switch(textField.tag) { //In case you want to handle multiple textfields
                case Constants.TAG1:
                    return newLength <= 20;
                case Constants.TAG2:
                    return newLength <= 30;
                default:
                    return newLength <= 15;
            }
        }
        return true;
    }

Write the condition in textfield delegate method as:-

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



    if (count(textField.text) > 4  && range.length == 0)

   {
        return false // return NO to not change text
    }
    else

    {

     }

write all your code part in else part.

The delegate methods or an NSFormatter such as NSNumberFormatter. The formatter is the most appropriate generally as it also provides localization support.

I know its bit too late but still I want share it too, I found a way which is much easier to set a limit character for an textfield in swift development.

Here is the code:-

import UIKit

private var maxLengths = [UITextField: Int]()

extension UITextField {

    @IBInspectable var maxLength: Int {
        get {
            guard let length = maxLengths[self] else {
                return Int.max
            }

            return length
        }
        set {
            maxLengths[self] = newValue
            addTarget(self, action: #selector(limitLength), for: .editingChanged)
        }
    }

    @objc func limitLength(textField: UITextField) {
        guard let prospectiveText = textField.text, prospectiveText.count > maxLength else {
            return
        }

        let selection = selectedTextRange
        let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)

        #if swift(>=4.0)
            text = String(prospectiveText[..<maxCharIndex])
        #else
            text = prospectiveText.substring(to: maxCharIndex)
        #endif

        selectedTextRange = selection
    }

}

and just set the limit through the panel.

Image: 在此处输入图片说明

Just try this to limit the length of TF

Editing changed Action Outlet of TF

@IBAction func otpTF2EditingChnaged(_ sender: UITextField) {
        if (sender.text?.count == 1) {
            otpTF3.becomeFirstResponder()
        }
        checkMaxLength(textField: sender , maxLength: 1)
    }

Function That will limit the length

private func checkMaxLength(textField: UITextField!, maxLength: Int) {
        if (textField.text!.count > maxLength) {
            textField.deleteBackward()
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM