iOS開發: 輸入框輸入內容長度限制優化 - 完整輸入最大限制的漢字

  • 目標效果: 在限制文本輸入長度的時候, 輸入漢字可以正常輸入最長限度


    目標效果
  • 在iOS開發中, 經常有輸入框輸入內容長度限制的需求, 如果我們只判斷輸入框文本長度, 然后進行切割, 那么就會在輸入漢字時無法正常輸入全部長度的漢字, 如下圖


    13.gif
  • 代碼如下

if (self.text.length > 10) {
    self.text = [self.text substringToIndex:10];
}

上述代碼雖然也做到了對輸入內容進行長度限制, 但是在輸入中文時的體驗并不是很好, 因為最后的幾個字如果拼音較長就很難輸入

  • 所以我們需要對限制長度的代碼進行優化, 讓用戶在輸入漢字時, 可以完整便捷的輸入最大長度的漢字, 就如最上方目標效果一樣
  • 優化代碼如下:
NSString *InputMethodType = [[UIApplication sharedApplication]textInputMode].primaryLanguage;

// 如果當前輸入法為漢語輸入法
if ([InputMethodType isEqualToString:@"zh-Hans"]) {
    
    // 獲取標記部分
    UITextRange *selectedRange = [self markedTextRange];
    
    //獲取標記部分, 此部分為用戶未決定輸入部分
    UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
    
    // 當沒有標記部分時截取字符串
    if (position == nil) {
        if (self.text.length > 10) {
            self.text = [self.text substringToIndex:10];
        }
    }
}else {
    if (self.text.length > 10) {
        self.text = [self.text substringToIndex:10];
    }
}
  • 下面是我寫的分類代碼, 可以在項目中直接使用
  • .h文件代碼
//
//  UITextField+LTExtension.h
//  LTTextField
//
//  Created by 冰凌天 on 2017/7/6.
//  Copyright ? 2017年 冰凌天. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UITextField (LTExtension)

/** 最大輸入長度 */
@property (nonatomic, assign) NSInteger maxInputLenght;

@end
  • .m文件代碼
//
//  UITextField+LTExtension.m
//  LTTextField
//
//  Created by 冰凌天 on 2017/7/6.
//  Copyright ? 2017年 冰凌天. All rights reserved.
//

#import "UITextField+LTExtension.h"
#import <objc/runtime.h>

static NSString *maxInputLenghtKey = @"maxInputLenghtKey";

@interface UITextField ()

/** 是否已經設置過最大值 */
@property (nonatomic, assign) NSInteger isSetupMaxInputLenght;

@end

@implementation UITextField (LTExtension)

#pragma mark - < 方法交換 >

+ (void)load
{
    Method dealloc = class_getInstanceMethod(self, NSSelectorFromString(@"dealloc"));
    Method lt_dealloc = class_getInstanceMethod(self, @selector(lt_dealloc));
    method_exchangeImplementations(dealloc, lt_dealloc);
    
    Method initWithFrame = class_getInstanceMethod(self, NSSelectorFromString(@"initWithFrame:"));
    Method lt_initWithFrame = class_getInstanceMethod(self, @selector(lt_initWithFrame:));
    method_exchangeImplementations(initWithFrame, lt_initWithFrame);
    
    
    Method initWithCoder = class_getInstanceMethod(self, NSSelectorFromString(@"initWithCoder:"));
    Method lt_initWithCoder = class_getInstanceMethod(self, @selector(lt_initWithCoder:));
    method_exchangeImplementations(initWithCoder, lt_initWithCoder);
}

- (void)lt_dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self lt_dealloc];
}

- (instancetype)lt_initWithFrame:(CGRect)frame
{
    [self lt_initWithFrame:frame];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lt_category_maxInputLenght_textDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:nil];
    
    return self;
}

- (instancetype)lt_initWithCoder:(NSCoder *)coder
{
    [self lt_initWithCoder:coder];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lt_category_maxInputLenght_textDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:nil];
    return self;
}

#pragma mark - < 屬性綁定 >

- (void)setMaxInputLenght:(NSInteger)maxInputLenght
{
    objc_setAssociatedObject(self, (__bridge const void *)(maxInputLenghtKey), @(maxInputLenght), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSInteger)maxInputLenght
{
    NSNumber *maxInputLenght = objc_getAssociatedObject(self, (__bridge const void *)(maxInputLenghtKey));
    return maxInputLenght.integerValue;
}

#pragma mark - < 輸入框內容處理 >

- (void)lt_category_maxInputLenght_textDidChangeNotification:(NSNotification *)notification
{
    if (self.maxInputLenght <= 0) return;
    
    NSString *InputMethodType = [[UIApplication sharedApplication]textInputMode].primaryLanguage;
    
    // 如果當前輸入法為漢語輸入法
    if ([InputMethodType isEqualToString:@"zh-Hans"]) {
        
        // 獲取標記部分
        UITextRange *selectedRange = [self markedTextRange];
        
        //獲取標記部分, 此部分為用戶未決定輸入部分
        UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
        
        // 當沒有標記部分時截取字符串
        if (position == nil) {
            if (self.text.length > self.maxInputLenght) {
                self.text = [self.text substringToIndex:self.maxInputLenght];
            }
        }
    }else {
        if (self.text.length > self.maxInputLenght) {
            self.text = [self.text substringToIndex:self.maxInputLenght];
        }
    }
}

@end
Swift版本
import UIKit

class LTTextField: UITextField {

    var maxInputlength = 0
    
    override var text: String? {
        didSet {
            self.textDidChange()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc fileprivate func textDidChange() {
    
        if maxInputlength <= 0 {
            return
        }
        
        let inputMethodType : String = UIApplication.shared.textInputMode?.primaryLanguage ?? ""
        
        if inputMethodType == "zh-Hans" {
            if let selectedRange = markedTextRange {
               let p = position(from: selectedRange.start, offset: 0)
                if p == nil {
                    if (text?.characters.count ?? 0) > maxInputlength {
                        text = (text! as NSString).substring(to: maxInputlength)
                    }
                }
            }else {
                if (text?.characters.count ?? 0) > maxInputlength {
                    text = (text! as NSString).substring(to: maxInputlength)
                }
            }
        }else {
            if (text?.characters.count ?? 0) > maxInputlength {
                text = (text! as NSString).substring(to: maxInputlength)
            }
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
  • 最后: 上面的內容如果有錯誤或者可優化的地方請留言, 我會進行修改
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容