Tuesday, October 1, 2013

How to set textView cursor position for last line in ios7?


The actual problem is textview's last line is not visible in ios7 when changing frame of textview, but perfectly visible in ios6. When i was working for project i get this kind of situation and today i will show you how to get rid of this problem. When you change frame of the textview when keyboard is appear, the last line of the textview is below the frame. By changing the shouldChangeTextInRange you will achieve the last line to visible inside the bound of the textview.

// This delegate method is implemented for remove last line hidden

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
       
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
       // ios7
        CGRect textRect = [textView.layoutManager usedRectForTextContainer:textView.textContainer];
        CGFloat sizeAdjustment = (textView.font.lineHeight * [UIScreen mainScreen].scale) + 5;
        
        if (textRect.size.height >= textView.frame.size.height - sizeAdjustment) 
       {
            if ([text isEqualToString:@"\n"]) 
           {
                [textView setContentOffset:CGPointMake(textView.contentOffset.x, textView.contentOffset.y + sizeAdjustment)];
                
            }
        }
    }
    else
    {
       // ios6
        [txtview scrollRangeToVisible:range];
        
        if ([text isEqualToString:@"\n"])
       {  
            [txtview setContentOffset:CGPointMake(txtview.contentOffset.x, txtview.contentOffset.y + 20)];
            
        }
        return YES;
    }
    return YES;
}

Hope, this Solution will save valuable  time for someone.