OC & Swift中UITextFiled、UITextView限制输入字数

OC中限制字数的方法

我是用通知实现的,首先添加UITextFiled和UITextView的接收中心

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewNotifitionAction:) name:UITextViewTextDidChangeNotification object:nil];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledNotifitionAction:) name: UITextFieldTextDidChangeNotification object:nil];
  

通知调用的方法

- (void)textViewNotifitionAction:(NSNotification *)userInfo{
    
    if (_textV.text.length>=10) {
        NSString *str = [_textV.text substringToIndex:10];
        _textV.text = str;
    }
    
}

- (void)textFieldNotifitionAction:(NSNotification *)userInfo{
    if (_textF.text.length>=10) {
        NSString *str = [_textF.text substringToIndex:10];
        _textF.text = str;
    }
}

Swift中限制字数的方法

设置接收中心

 NotificationCenter.default.addObserver(self, selector: #selector(textViewNotifitionAction), name: NSNotification.Name.UITextViewTextDidChange, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(textFiledNotifitionAction), name: NSNotification.Name.UITextFieldTextDidChange, object: nil);

通知调用的方法

func textViewNotifitionAction(userInfo:NSNotification){
        let textVStr = textV.text as NSString;
        if (textVStr.length >= 10) {
            let str = textVStr.substringToIndex(10);
            textV.text = str;
        }
        
    }
func textFiledNotifitionAction(userInfo:NSNotification){
        let textFStr = textF.text! as NSString;
        if (textFStr.length >= 10) {
            let str = textFStr.substringToIndex(10);
            textF.text = str;
        }
        
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容