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

OC中限制字数的方法

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

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

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldNotifitionAction:) 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中限制字数的方法

设置接收中心

NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewNotifitionAction:", name: UITextViewTextDidChangeNotification, object: nil); 
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFiledNotifitionAction:", name: UITextFieldTextDidChangeNotification, 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; } }

转载于:https://www.cnblogs.com/zxh-iOS/p/5902743.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值