限制UITextView中的字数

      很多时候我们想限制textView中的输入字数,我们可以利用函数- (void)textViewDidChange:(UITextView *)textView中统计textView实现此功能。通过在此函数中统计你输入的字符的个数,当字数超过你限制的字数时调用函数-(NSString *)substringToIndex:(int)length(length是你想限制的字数).这样当你输入的字符达到限定的个数时,将无法在往textView中输入数据。(实际上是你新输入的数据被函数-(NSString *)substringToIndex:(int)length截掉了。)。还有就是在textView中默认的是一行输入,如果想实现多行输入,需要设置它的scrollEnabled属性。例如:textView.scrollEnabled = YES;如果想直接让用户不能在textView中编辑,只能阅读 可以设置textView的editable属性。例如textView.editable = YES(可以编辑。下面这行代码实现的是限制textView的字数在128以内。如果超过次数会弹出警告。(其中statusLabel动态的显示textView中的字符个数)。

- (void)textViewDidChange:(UITextView *)textView {
    NSInteger number = [textView.text length];
    if (number > 128) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"字符个数不能大于128" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        textView.text = [textView.text substringToIndex:128];
        number = 128;
        [alert release];
    }
    self.statusLabel.text = [NSString stringWithFormat:@"%d/128",number];
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值