iOS开发-UITextView字数限制方法-UITextView使用详细

本文介绍如何正确使用 UITextView 进行文本编辑,并通过实例演示了如何设置 UITextView 的属性、限制输入字数及实现输入状态的实时反馈。

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

TextView是我们常见的文本编辑框,在使用的时候很多人把他当做texfield使用,这是错误的,以下是textcview的使用,包括协议:在开头声明<UITextViewDelegate>

// 初始化
text1 = [[UITextViewalloc]initWithFrame:CGRectMake(0,20, _vv2.frame.size.width,150)];
text1.delegate =self;
text1.textColor = [UIColorwhiteColor];
text1.backgroundColor = [UIColorblackColor];
text1.font = [UIFontsystemFontOfSize:16];

// 用协议限制字数
- (BOOL)textView:(UITextView *)atextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.location >50) {
        returnNO;
    }else
    {
        returnYES;
    }
}
// textview的触发事件
-(void)textViewDidChange:(UITextView *)textView
{
    NSInteger a;
    a = 50 - textView.text.length;
    
    if (a >=0) {
        NSString * str = [NSStringstringWithFormat:@"还可以输入%ld字",a];
        count.text = str;
    }else
    {
        count.text =@"字数已满";
    }
    
    if (text1.text.length ==0) {
        lable.text =@"请输入您的宝贵意见";
    }else{
        lable.text =@"";
    }
    NSLog(@"%ld",text1.text.length);
}
// 两个lable放在textview里面
lable = [[UILabelalloc]initWithFrame:CGRectMake(0,5, 100,20)];
lable.text =@"请输入内容";
lable.textColor = [UIColorlightGrayColor];
lable.font = [UIFontsystemFontOfSize:16];

count = [[UILabelalloc]initWithFrame:CGRectMake(0,text1.frame.size.height -20, text1.frame.size.width - 100, 20)];
count.text =@"还可以输入50字";
count.textColor = [UIColorlightGrayColor];
count.font = [UIFontsystemFontOfSize:16];

以下是效果图:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值