UITextView(UITextField)的內(nèi)容長(zhǎng)度限制

項(xiàng)目完成后,閑逛時(shí)候發(fā)現(xiàn)了這個(gè)文章 再談multistage text input(中文輸入法)下UITextView的內(nèi)容長(zhǎng)度限制,有一些內(nèi)容實(shí)現(xiàn)的不太一樣,分享一下。

先說(shuō)下原則。輸入的文字,只有拼接后才知道真正的長(zhǎng)度,所以,先拼接好字符串,然后在textfielddidchangge里面設(shè)置字符串。

但是,在textViewDidChange: 方法中去處理已經(jīng)晚了,所以判斷及整合,都要在- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text中處理。聯(lián)想輸入、不定長(zhǎng)度的粘貼,都會(huì)體現(xiàn)出來(lái)。這里唯一不完美的是emoji表情,在拼接的時(shí)候檢測(cè)長(zhǎng)度有點(diǎn)問(wèn)題。

這里控制了三個(gè)textField,并顯示長(zhǎng)度。

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string{

if([stringisEqual:@""]) {

returnYES;

}

NSString*temp = [textField.textstringByReplacingCharactersInRange:rangewithString:string];

NSString*tempStr = temp;// stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

if(textField ==self.hospitalTextField|| textField ==self.departmentTextField){

if(tempStr.length>30)returnNO;

}elseif(textField ==self.diseaseNameTextField){

if(tempStr.length>20)returnNO;

}

returnYES;

}

因?yàn)槭侨恐匦绿鎿Q的text,所以還要設(shè)置selectedTextRange

- (void)textFieldCountLabelChange:(UITextField *)textField{

NSString *tempStr = [textField.text copy];

UITextRange *selRange = textField.selectedTextRange;

UILabel *label;

inttotal =30;

if(textField ==self.hospitalTextField ){

total =30;

label =self.hosptalCountLabel;

}elseif(textField ==self.departmentTextField){

total =30;

label =self.departmentCountLabel;

}elseif(textField ==self.diseaseNameTextField){

total =20;

label =self.diseaseNameCountLabel;

}

if(tempStr.length > total) {

textField.text = [tempStr substringToIndex:total];

textField.selectedTextRange = selRange;

}

intcount = total - (int)textField.text.length;

if(count <0) {

count =0;

}

label.text = [NSString stringWithFormat:@"%d", count];

}

第一篇文章先這樣,不好的地方以后再修改。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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