How to scroll `UITextView` programmatically when user enters each line? - iphone

How can I scroll my UITextView programmatically when user enters each line.
It is necessary for my textView since keypad hides it at some point as shown below.
I searched lot, but didn't found any appropriate solution, as I am a newbie to iPhone development. I need your valuable help.

when you are opening the keyboard, you should adjust the frame of your textview. In this case reduce the height of your frame by the height of keyboard.
Implement proper code for these two delegate methods.
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
CGRect frm = textView.frame;
frm.height -= KEY_BOARD_HEIGHT;
textView.frame = frm;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView;
{
CGRect frm = textView.frame;
frm.height += KEY_BOARD_HEIGHT;
textView.frame = frm;
}

Take a variable for Scrolling position :: int scrollY;
Code for TextView ::
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:#"\n"])
{
scrollY += 10;
scrMain.contentOffset = CGPointMake(0, scrollY);
}
return YES;
}
Then, when user resign from keyboard, set it to again 0 and scroll to its origin position.
scrollY = 0;
scrMain.contentOffset = CGPointMake(0, 0);
Hope, it may help you.
Thanks.

UITextView scroll text automatically when enter text, you only change UITextView frame to above keyboard and when you dismiss key board reset UITextView frame
- (void)textViewDidBeginEditing:(UITextView *)textView
{
//set frame for text view here
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
//set frame for text view here
}

Related

Scroll on textField when begin Editing and keyboard appear

I've a viewController composed by an UIImageView that fills the whole view and two textField located at the center of the view. All this is located inside a ScrollView.
I use Storyboard and I disabled the autolayout.
When I click on a textField, and thus opens the keyboard, I'd like that the scroll is displaced directly on textField. How can I do that?
Consider that your TextField outlet is named txtField then implement UITextField Delegate using
txtField.delegate = self;
Considering that your ScrollView outlet is named scrollView. Implement the Textfield Delegate method:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(#"%#",NSStringFromCGRect(textField.frame));
[scrollView scrollRectToVisible:textField.frame animated:YES];
}
Hope this helps.
Do let me know if you need more help.
I usually use this successfully:
http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
Add your controller as an observer of the keyboard notifications. When you receive the notification, resize the scroll view frame and / or set the content offset (depending on the exact effect you want and content size you have).
Here are several options that I've used before:
Apple's Doco. See the section titled Moving Content That Is Located Under the Keyboard
Cocoa With Love article, Sliding UITextFields around to avoid the keyboard
If you have several text fields or other form elements in your view, you could alternatively use something like EZForm. It does automatic repositioning of views to keep input fields visible, and also handles input validation and other useful form-related stuff.
You can convert the text field coordinate system into Scroll view coordinate system. Use the below code
-(void)rearrangeView{
// previous
if (txtActiveField == txtUsername) {
CGPoint pt;
CGRect rc = [txtUsername bounds];
rc = [txtUsername convertRect:rc toView:scrollViewLogin];
pt = rc.origin;
pt.x = 0;
pt.y -= 40;
[scrollViewLogin setContentOffset:pt animated:YES];
}
else if (txtActiveField == txtPassword) {
// [self.txtEmail becomeFirstResponder];
CGPoint pt;
CGRect rc = [txtPassword bounds];
rc = [txtPassword convertRect:rc toView:scrollViewLogin];
pt = rc.origin;
pt.x = 0;
pt.y -= 40;
[scrollViewLogin setContentOffset:pt animated:YES];
}
}
#pragma mark- UITextField Delegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
txtActiveField = textField;
//txtActiveField.placeholder = #"";
[self rearrangeView];
return YES;
}
Here txtActiveField is instance variable of type UItextField

Text view scrolling with in a limited frame in iphone?

I had a text view above the keyboard like hangout application in iphone. i need to type the character in that as go on it will increses the content scroll with in that frame only.and also the texts needs to be in the correct allignment,I did that in this manner `
-(void)textViewDidChange:(UITextView *)textView
{
NSString *text1 = [textView text];
CGFloat width = [textView frame].size.width;
CGSize size = [text1 sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(width, 9999) lineBreakMode:UILineBreakModeWordWrap];
textView.contentSize=CGSizeMake([textView frame].size.width, size.height) ;
}
- (BOOL)textViewShouldReturn:(UITextView *)textview
{
[textView1 resignFirstResponder];
return YES;
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textField
{
//delegate=self;
return YES;
}
`But here the problem is it is dancing .not sticking.when ever i am typing the whole area is moving up and down,i need it to be fixed.and when ever i typed and reached the end point it needs to scroll up.Can any body help me in where i am going wrong?
For set contentSize of UITextView no need any code , by default it provides this so remove your whole code from textViewDidChange: method.
txtView.contentSize = CGSizeMake(320, 800);
Try this and put dis textview on scrollview.

Scrolling when the keyboard activated

I have an app where you have textfields and one textview but when I get the keyboard it hides the lower textfields. How would I do it.
I have tried:
.m:
- (void)textFieldDidBeginEditing:(UITextField *)sender {
CGSize content = _scrollView.contentSize;
_scrollView.contentSize = CGSizeMake(content.width, content.height + 200);
svos = _scrollView.contentOffset;
CGPoint pt;
CGRect rc = [sender bounds];
rc = [sender convertRect:rc toView:_scrollView];
pt = rc.origin;
pt.x = 0;
pt.y -= 200;
[_scrollView setContentOffset:pt animated:YES];
}
- (IBAction)textFieldShouldReturn:(UITextField *)textField {
CGSize content = _scrollView.contentSize;
_scrollView.contentSize = CGSizeMake(content.width, content.height - 200);
[_scrollView setContentOffset:svos animated:YES];
[textField resignFirstResponder];
}
.h:
CGPoint svos;
Although the bottom text fields are still hidden it does scroll to the visible ones
You have obtained the origin of the sender textfield but only move up by 60, thus, the lower textfields are covered by the keyboard. You will need to know the height of the keyboard and calculate the distance to move up. Check this out. It has much of the answer so I will not explain again.
To scroll to the bottom textfield inside a scrollview, add these lines in textFieldDidBeginEditing:
CGSize content = _scrollview.contentSize;
_scrollview.contentSize = CGSizeMake(content.width, content.height + 200);
This will extend your contentSize programmatically so you can scroll to the last textfield and allow the keyboard to cover the empty space.
In textFieldDidEndEditing or textFieldShouldReturn, in your case, add these:
CGSize content = _scrollview.contentSize;
_scrollview.contentSize = CGSizeMake(content.width, content.height - 200);
I used an arbitrary 200 as example. You will need to figure out how much you want.
A drop-in universal solution for moving text fields out of the way of the keyboard in iOS
https://github.com/michaeltyson/TPKeyboardAvoiding
It works perfect for me.
Simply you need to copy the required classes(TPKeyboardAvoidingScrollView or TPKeyboardAvoidingTableView) in your project and in your interface builder file you have to change the UIScrollView class to TPKeyboardAvoidingScrollView or UITableView to TPKeyboardAvoidingTableView, the remaining things will be handled by these classes.
Have you seen the documentation about managing the keyboard? (apple documentation) There is an example of what i think you are working on. Hope it helps.

changing the frame of UITextView as I am typing

I can use the code below to set the size of the textView frame, to approximately match the textView's content (the typed text) when I press a button or whatnot. How would I call this whenever a new character is typed, so that the frame would grow or shrink interactively?
- (IBAction)doneEditingText:(id)sender {
[myTextView resignFirstResponder];
[myTextView setFrame:CGRectMake(myTextView.frame.origin.x, myTextView.frame.origin.y, myTextView.contentSize.width, myTextView.contentSize.height)];
}
Thanks for reading
EDIT :
Implement UITextView delegate in .h file this:
#interface ViewController : UIViewController<UITextViewDelegate>
If yourTextView added from xib then bind delegate with fileowner otherwise in ViewDidLoad add this line:
yourTextView.delegate = self;
Use textView's delegate for your requirement:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
CGSize maximumSize = CGSizeMake(280,999); //specify width of textView and maximum height for text to fit in width of textView
CGSize txtSize = [textView.text sizeWithFont:[UIFont fontWithName:#"Arial" size:16] constrainedToSize:maximumSize lineBreakMode:UILineBreakModeCharacterWrap]; //calulate size of text by specifying font here
//Add UIViewAnimation here if needed
[textView setFrame:CGRectMake(textView.frame.origin.x,textView.frame.origin.y,txtSize.width+10,txtSize.height+10)]; // change accordingly
return YES;
}
You can use something like this repo on GIT which has the almost same functionality that you want-
https://github.com/HansPinckaers/GrowingTextView
it's similar like message app in iPhone.
I just got done implementing this. The problem with the current (as of posting this answer) accepted answer is that the delegate method:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
exposes the textView before the change the user has typed/inserted/deleted is commited. therefore, the resizing you would be achieving would be one character late. UITextView does inherit from a UIScrollView so the text wouldn't clip off of screen but it could lead to some awkward behavior.
My Solution is to use two delegate methods to achieve the resizing effect correctly.
Expanding the UITextView before the character the user typed hits the screen:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSMutableString *tempString = [NSMutableString stringWithString:textView.text];
[tempString replaceCharactersInRange:range withString:text];
//If we are adding to the length of the string (We might need to expand)
if([tempString length]>textView.text.length)
{
//Create a temporaryTextView which has all of the characteristics of your original textView
UITextView *tempTextView = [[UITextView alloc] initWithFrame:CGRectZero];
tempTextView.font = _inputFont;
tempTextView.contentInset = textView.contentInset;
[tempTextView setText:tempString];
//Change this to respect whatever width constraint you are trying to achieve.
CGSize theSize = [tempTextView sizeThatFits:CGSizeMake(192, CGFLOAT_MAX)];
if(theSize.height!=textView.frame.size.height)
{
textView.frame = CGRectMake(115, 310, 192,theSize.height);
return YES;
}
else
{
return YES;
}
}
else
{
return YES;
}
}
And Shrinking after the user has deleted/shrunk the amount of text in the UITextView the character
-(void)textViewDidChange:(UITextView *)textView
{
//We enter this method AFTER the edit has been drawn to the screen, therefore check to see if we should shrink.
if([textView sizeThatFits:CGSizeMake(192, CGFLOAT_MAX)].height!=textView.frame.size.height)
{
//change this to reflect the constraints of your UITextView
textView.frame = CGRectMake(115, 310, 192,[textView sizeThatFits:CGSizeMake(192, CGFLOAT_MAX)].height);
}
}

Scrolling in a table

in my table I use cells with UITextField as subview. I also can edit it but only for the upper cells in the table I also see, what I edit, because the keyboard hides the lower cells.
Now what must I do, to scroll the cell I whant to edit move to the top?
I tried
selectRowAtIndexPath:indexPathOfCurrrentCell animated:NO scrollPostion:UITableViewSchrollPositionTop
and
scrollToRowAtIndexPath:idexPathOfCurrentCell atScrollPosition:UITableViewSchrollPositionTop animated:NO
but none of it works. Must I use an other command or add something additional? What must I change?
Thanks
If you can't manually scroll the tableView to somewhere where the cell is visible; the code won't either.
The solution is to set the frame of the tableView to have a height that respects the keyboard's height of 170 points.
You could try something like this:
tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width, tableView.frame.size.height-170);
Do this in your method which gets called when the textField becomes the first responder.
Take a look at this post. I think you'll find what you need.
Get UITableView to scroll to the selected UITextField and Avoid Being Hidden by Keyboard
Use Delegate Method of UITextField
Even I encountered this scrolling problem and i use the below logic to get rid of this.
This Works fine
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
if (textField==textFieldOfYourInterest )
{
CGRect frame = self.view.frame;
if ([textField isFirstResponder] && self.view.frame.origin.y >= 0)
{
frame.origin.y -= 70;
}
else if (![textField isFirstResponder] && self.view.frame.origin.y < 0)
{
frame.origin.y += 70;
}
[self.view setFrame:frame];
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
CGRect frame = self.view.frame;
if (![topTextFieldName isFirstResponder] && self.view.frame.origin.y < 0)
{
frame.origin.y += 70;
}
[self.view setFrame:frame];
NSLog(#"text field should return");
[textField resignFirstResponder];
return YES;
}
If any problem revert to me.
Thanks
Nagaraja Sathe