当我加载一个UIView时,我如何在iPhone SDK上设置UITextField的最大字符数?


当前回答

美国小妞Xamarin:

YourTextField.ShouldChangeCharacters = 
delegate(UITextField textField, NSRange range, string replacementString)
        {
            return (range.Location + replacementString.Length) <= 4; // MaxLength == 4
        };

其他回答

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.text.length >= 50) {
        return NO;
    }
    return YES;
}

有通用的解决方案设置最大长度在Swift。 通过IBInspectable,你可以在Xcode属性检查器中添加新的属性。

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:"),
                forControlEvents: UIControlEvents.EditingChanged
            )
        }
    }

    func limitLength(textField: UITextField) {
        guard let prospectiveText = textField.text
            where prospectiveText.characters.count > maxLength else {
                return
        }
        let selection = selectedTextRange
        text = prospectiveText.substringWithRange(
            Range<String.Index>(prospectiveText.startIndex ..< prospectiveText.startIndex.advancedBy(maxLength))
        )
        selectedTextRange = selection
    }

}

我在Swift中这样做是为了在使用数字垫时限制8个字符。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    return !(textField.text?.characters.count == MAX_LENGTH && string != "")
}

我必须测试string != ""以允许删除按钮在数字板上工作,否则它将不允许在达到最大值后删除文本字段中的字符。

我创建了这个UITextFieldLimit子类:

支持多个文本框 设置文本长度限制 粘贴的预防 在文本域中显示左字符的标签,当您停止编辑时隐藏。 当没有字符时摇动动画。

获取UITextFieldLimit.h和UITextFieldLimit。m从这个GitHub存储库:

https://github.com/JonathanGurebo/UITextFieldLimit

开始测试吧!

标记你的故事板创建的UITextField,并使用身份检查器链接到我的子类:

然后可以将其链接到IBOutlet并设置限制(默认为10)。


你的ViewController.h文件应该包含:(如果你不想修改设置,比如限制)

#import "UITextFieldLimit.h"

/.../

@property (weak, nonatomic) IBOutlet UITextFieldLimit *textFieldLimit; // <--Your IBOutlet

ViewController。m文件应该@synthesize textFieldLimit。


在ViewController中设置文本长度限制。m文件:

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    [textFieldLimit setLimit:25];// <-- and you won't be able to put more than 25 characters in the TextField.
}

希望这门课能帮到你。好运!

斯威夫特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
    }
}

编辑:内存泄漏问题修复。