Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView : Text starts from 2nd line of text view

I have a strange problem. I have 3 UITextFields and one UITextView. I can move from one UITextFieldto next UITextField by:

- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
    NSInteger nextTag = textField.tag + 1;
    //-- try to find next responde
    UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];

    if (nextResponder) 
    {
        //-- found next responce ,so set it
        [nextResponder becomeFirstResponder];
    }
    else
    {
        [scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        //-- not found remove keyboard
        [textField resignFirstResponder];
        return YES;
    }   

    return YES;
}

Its all works fine until it comes to UITexView, then my cursor moves at 2nd line of the text view in place of 1st line of text view.

Text view is taken from IB.

The code for text view:

- (void) textViewDidBeginEditing:(UITextView *)textView
{
    optionalText.hidden = YES ;
    [scrollView setContentOffset:CGPointMake(0, textView.center.y-100) animated:YES];
}

- (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{       
    // Any new character added is passed in as the "text" parameter
    if ([text isEqualToString:@"\n"])
    {
        // Be sure to test for equality using the "isEqualToString" message
        [textView resignFirstResponder];
        [scrollView setContentOffset:CGPointMake(0, 0) animated:YES];

        // Return FALSE so that the final '\n' character doesn't get added      
        if ([[commentTxtView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0)
        {
            optionalText.hidden = NO ;
            NSLog(@"Text View is null");
            [scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }

        return FALSE;
    }

    return TRUE;
}

It looks like this:

enter image description here

What could be the problem? Why does it not start from 1st line of text view?

like image 329
Maulik Avatar asked Nov 07 '11 14:11

Maulik


2 Answers

I bet your textFieldShouldReturn: should return NO in case the nextResponder is your UITextField. Right now you are always returning YES, which means that the key probably being passed to the UITextView, which will then insert the new line.

like image 111
Stefan Arentz Avatar answered Oct 20 '22 01:10

Stefan Arentz


For Anybody coming in looking for Swift 2.0 translation...

Instead of returning true in textFieldShouldReturn after yourUIITextView.becomeFirstResponder(), return false.

Worked for me!

Hope this helps!

like image 44
justColbs Avatar answered Oct 20 '22 03:10

justColbs