给键盘添加确认/剩余字数按钮,并且改变超过剩余个数局部文字颜色

eg:




@property (nonatomic, strong) UILabel *remainLabel;

@property (nonatomic, strong) UIButton *completeBut;



//  关于View和but的配置


- (void)setUpWithKeyBoardView {

    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];

    

    UIBarButtonItem *remin = [[UIBarButtonItem alloc]initWithCustomView:self.remainLabel];

    UIBarButtonItem *complete = [[UIBarButtonItem alloc] initWithCustomView:self.completeBut];

    

    

    NSArray * buttonsArray = [NSArray arrayWithObjects:remin,complete,nil];

    [topView setItems:buttonsArray];


//  重点在这句,设置键盘的setInputAccessoryView,将按钮添加至topView

    [self.infoTextview setInputAccessoryView:topView];

}



//  AccessoryView

- (UILabel *)remainLabel {

    if (!_remainLabel) {

        _remainLabel = [[UILabel alloc] init];

        _remainLabel.text = @"0/10";

        _remainLabel.font = [UIFont systemFontOfSize:15.0f];

        _remainLabel.textAlignment = NSTextAlignmentLeft;

        _remainLabel.frame = CGRectMake(5, 0, ScreenWidth-100, 30);

    }

    return _remainLabel;

}

- (UIButton *)completeBut {

    if (!_completeBut) {

        _completeBut = [UIButton buttonWithType:UIButtonTypeCustom];

        [_completeBut setTitle:@"完成" forState:UIControlStateNormal];

        [_completeBut setFont:[UIFont systemFontOfSize:15.0f]];

        [_completeBut addTarget:self action:@selector(completeButAction) forControlEvents:UIControlEventTouchUpInside];

        [_completeBut setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

        _completeBut.frame = CGRectMake(0, 0, 80, 30);

    }

    return _completeBut;

}



// 方法

-(void)completeButAction

{

    [self.infoTextview resignFirstResponder];

}




// 设置一下delegate

    self.infoTextview.delegate = self;


// 监测一下键盘文字上的变化

- (void)textViewDidChange:(UITextView *)textView {


    NSString *str = [NSString stringWithFormat:@"%ld/300",textView.text.length];


    // 判断文字是否超过10个字,超过设置文字为红色

    if (textView.text.length > 10) {

        

        

        NSMutableAttributedString *attrDescribeStr = [[NSMutableAttributedString alloc] initWithString:str];

        

        [attrDescribeStr addAttribute:NSForegroundColorAttributeName

                                value:[UIColor redColor]

//  range:设置改变文本颜色的范围

                                range:[str rangeOfString:[NSString stringWithFormat:@"%ld",textView.text.length]]];

        self.remainLabel.attributedText = attrDescribeStr;

        

    } else {

        self.remainLabel.text = str;

    }


    

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值