UITextView實(shí)現(xiàn)字?jǐn)?shù)限制

UITextView使用相對較少,研究了下發(fā)現(xiàn)代理方法并不多,算是簡單控件了。這里針對字?jǐn)?shù)限制功能的開發(fā)稍作總結(jié):

//創(chuàng)建UITextView,注意添加代理
    UITextView *textView = [[UITextView alloc]init];
    textView.text = @"占位文字";
    textView.delegate = self;       //UITextViewDelegate
    textView.textColor = hexStringToColor(@"C2C2C2");
    textView.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:textView];
    [textView makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15*layoutBy6());
        make.top.mas_offset(10*layoutBy6());
        make.right.mas_offset(-15*layoutBy6());
        make.bottom.mas_offset(-10*layoutBy6());
    }];
#pragma mark - TextViewDelegate
//輸入時(shí)自動刪除占位文字
- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"占位文字"]) {
        textView.text = @"";
    }
}

//當(dāng)編輯時(shí)動態(tài)判斷是否超過規(guī)定字?jǐn)?shù),這里限制20字
- (void)textViewDidChange:(UITextField *)textView{
    
    if (textView.text.length > 20) {
        textView.text = [textView.text substringToIndex:20];
    }
//這里的_strLengthLbl為動態(tài)顯示已輸入字?jǐn)?shù),可按情況添加
    _strLengthLbl.text = [NSString stringWithFormat:@"%lu/20",textView.text.length];
}

//編輯結(jié)束后如內(nèi)存為空自動添加占位文字
- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"占位文字";
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容