iOS UITextView限制字数

本文介绍如何在iOS应用中使用UITextView实现输入字符数量限制,并添加占位符提示信息。通过代码示例展示了如何监听并计算剩余可输入字符数,并在界面上实时更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//UITextVIew输入框

self.contentTV = [[UITextView alloc] initWithFrame:CGRectMake(0, lineVIewOne.frame.origin.y+lineVIewOne.frame.size.height+1,self.view.frame.size.width, 160)];

self.contentTV.backgroundColor = [UIColor whiteColor];

self.contentTV.textAlignment = NSTextAlignmentLeft;

//self.contentTV.text = @"您在使用中有遇到什么问题?可以向我们及时反馈噢!";

self.contentTV.font = [UIFont systemFontOfSize:14.0];

self.contentTV.keyboardType = UIKeyboardTypeNamePhonePad;

self.contentTV.clearsOnInsertion = YES;

[self.view addSubview:self.contentTV];

self.contentTV.delegate = self;

self.placehoderLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.contentTV.frame.size.width, 30)];

self.placehoderLabel.backgroundColor = [UIColor whiteColor];

self.placehoderLabel.text = @"您在使用中有遇到什么问题?可以向我们及时反馈噢!";

//self.placehoderLabel.alpha = 0.5;

//self.placehoderLabel.textAlignment = NSTextAlignmentCenter;

self.placehoderLabel.font = [UIFont systemFontOfSize:13.0];

[self.contentTV addSubview:self.placehoderLabel];

 

#pragma mark - UITextViewDelegate

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{

NSString *temp = [textView.text

stringByReplacingCharactersInRange:range

withString:text];

 

NSInteger remainTextNum = 100;

//计算剩下多少文字可以输入

if(range.location>=100)

{

remainTextNum = 0;

[self showSimpleAlert:@"请输入小于100个字!"];

self.emailFT.userInteractionEnabled = NO;

return YES;

}

else

{

NSString * nsTextContent = temp;

NSInteger existTextNum = [nsTextContent length];

remainTextNum =100-existTextNum;

self.label = [[UILabel alloc] initWithFrame:CGRectMake(textView.frame.size.width-80, textView.frame.size.height-30, 80, 30)];

self.label.textAlignment = NSTextAlignmentCenter;

[textView addSubview:self.label];

self.label.backgroundColor = [UIColor whiteColor];

self.label.text = [NSString stringWithFormat:@"%ld/100",(long)remainTextNum];

return YES;

}

}

 

 

当你输入的时候,label上会显示还剩余多少字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值