TextView与键盘隐藏

时间:2014-01-22 08:20:22

标签: ios iphone

我有TextView.In TextView我必须设置最多160个字符到TextView包括空格。如果我点击返回键盘应该下降。我有编码。它只在输入160个字符后才能工作。所以如果我点击重新调整,即时它应该下降,它不应该是160个字符,包括空格。即使我输入“你好吗?”后点击返回。在文本视图中,键盘应隐藏。

我的编码是

 -(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;

        }


}

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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:第二部分来自here的这个rebito答案。所以,归功于他......