2014-01-22 120 views
0

我有TextView.In TextView我必須設置最大160個字符到TextView包括空間。如果我點擊返回鍵盤應該down.I有編碼。它工作後輸入160字符only.So如果我點擊retun,緊緊地它應該下去,它不應該在160個字符之後包括空格。即使我在點擊回車後進入「你好嗎?」。在文本視圖中,鍵盤應該隱藏。TextView與鍵盤隱藏

我的編碼是

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

{ 

    //First type for space 

    /* 
    return txtviewAsk.text.length + (text.length - range.length) <= 160; 
    [txtviewAsk resignFirstResponder]; 
    */ 

    //Second type with correct method 

    NSUInteger newLength = (textView.text.length - range.length) + text.length; 
    if(newLength <= MAX_LENGTH) 
    { 
     //[txtview resignFirstResponder]; 
      return YES; 
    } 
    else 
    { 
     NSUInteger emptySpace = MAX_LENGTH - (textView.text.length - range.length); 
     textView.text = [[[textView.text substringToIndex:range.location] 
         stringByAppendingString:[text substringToIndex:emptySpace]] 

        stringByAppendingString:[textView.text substringFromIndex:(range.location + range.length)]]; 


     [txtviewAsk resignFirstResponder]; 
     return NO; 

     } 


} 
+0

結帳這個答案http://stackoverflow.com/questions/703754/how-to-dismiss-keyboard-for-uitextview-with-return-key – Divya

回答

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

    if(textView.text.length >=160) 
    { 
     [textView resignFirstResponder]; 
     return NO; 

    } 
    if([text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location == NSNotFound) { 
    return YES; 

    } 

    [textView resignFirstResponder]; 
    return NO; 
} 

基本上,第一部分是檢查長度並結束編輯和第二部分是用於返回鍵..

PS:第二部分來自這個rebito從here的答案。所以,信貸去他..

+0

謝謝你的編碼。 – user3182143

0
Add return no to the below of the if condition. 
if(newLength <= MAX_LENGTH) 
{ 
    if ([textView.text isEqualToString:@"\n"]) { 
      [textView resignFirstResponder]; 
      return NO; 
      } 
    return YES; 
}