Set the maximum character length of a UITextField

前端 未结 30 1692
难免孤独
难免孤独 2020-11-22 02:27

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

相关标签:
30条回答
  • 2020-11-22 03:04

    Swift 3 version //***** This will NOT work with Swift 2.x! *****//

    First create a new Swift file : TextFieldMaxLength.swift, and then add the code below:

    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: UIControlEvents.editingChanged
          )
       }
    }
    func limitLength(textField: UITextField) {
        guard let prospectiveText = textField.text,
            prospectiveText.characters.count > maxLength
        else {
            return
        }
    
       let selection = selectedTextRange
       let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
       text = prospectiveText.substring(to: maxCharIndex)
       selectedTextRange = selection
       }
    }
    

    and then you will see in Storyboard a new field (Max Length) when you select any TextField

    if you still have more questions check out this link: http://www.globalnerdy.com/2016/05/18/ios-programming-trick-how-to-use-xcode-to-set-a-text-fields-maximum-length-visual-studio-style/

    0 讨论(0)
  • 2020-11-22 03:05

    Swift 4

    import UIKit
    
    private var kAssociationKeyMaxLength: Int = 0
    
    extension UITextField {
        
        @IBInspectable var maxLength: Int {
            get {
                if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
                    return length
                } else {
                    return Int.max
                }
            }
            set {
                objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
                addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
            }
        }
        
        @objc func checkMaxLength(textField: UITextField) {
            guard let prospectiveText = self.text,
                prospectiveText.count > maxLength
                else {
                    return
            }
            
            let selection = selectedTextRange
            
            let indexEndOfText = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
            let substring = prospectiveText[..<indexEndOfText]
            text = String(substring)
            
            selectedTextRange = selection
        }
    }
    

    Edit: memory leak issue fixed.

    0 讨论(0)
  • 2020-11-22 03:05

    What about this simple approach. Its working fine for me.

    extension UITextField {
    
        func  charactersLimit(to:Int) {
    
            if (self.text!.count > to) {
                self.deleteBackward()
            }
        }
    }
    

    Then:

    someTextField.charactersLimit(to:16)
    
    0 讨论(0)
  • 2020-11-22 03:05

    For Xamarin:

    YourTextField.ShouldChangeCharacters = 
    delegate(UITextField textField, NSRange range, string replacementString)
            {
                return (range.Location + replacementString.Length) <= 4; // MaxLength == 4
            };
    
    0 讨论(0)
  • 2020-11-22 03:06

    I have implemented a UITextField Extension to add a maxLength property to it.

    It's based on Xcode 6 IBInspectables, so you can set the maxLength limit on the Interface builder.

    Here is the implementation:

    UITextField+MaxLength.h

    #import <UIKit/UIKit.h>
    
    @interface UITextField_MaxLength : UITextField<UITextFieldDelegate>
    
    @property (nonatomic)IBInspectable int textMaxLength;
    @end
    

    UITextField+MaxLength.m

    #import "UITextField+MaxLength.h"
    
    @interface UITextField_MaxLength()
    
    @property (nonatomic, assign) id <UITextFieldDelegate> superDelegate;
    
    @end
    
    @implementation UITextField_MaxLength
    
    - (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
        //validate the length, only if it's set to a non zero value
        if (self.textMaxLength>0) {
            if(range.length + range.location > textField.text.length)
                return NO;
    
            if (textField.text.length+string.length - range.length>self.textMaxLength) {
                return NO;
            }
        }
    
        //if length validation was passed, query the super class to see if the delegate method is implemented there
        if (self.superDelegate && [self.superDelegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
            return [self.superDelegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
        }
        else{
            //if the super class does not implement the delegate method, simply return YES as the length validation was passed
            return YES;
        }
    }
    
    - (void)setDelegate:(id<UITextFieldDelegate>)delegate {
        if (delegate == self)
            return;
        self.superDelegate = delegate;
        [super setDelegate:self];
    }
    
    //forward all non overriden delegate methods
    - (id)forwardingTargetForSelector:(SEL)aSelector {
        if ([self.superDelegate  respondsToSelector:aSelector])
            return self.superDelegate;
    
        return [super forwardingTargetForSelector:aSelector];
    }
    
    - (BOOL)respondsToSelector:(SEL)aSelector {
        if ([self.superDelegate respondsToSelector:aSelector])
            return YES;
    
        return [super respondsToSelector:aSelector];
    }
    @end
    
    0 讨论(0)
  • 2020-11-22 03:07

    You can't do this directly - UITextField has no maxLength attribute, but you can set the UITextField's delegate, then use:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    
    0 讨论(0)
提交回复
热议问题