scroll textfield covered by keyboard - iphone

Im working on getting my UIscroll to scroll when ever a textfield is blocked by the keyboard by following this documentation
http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW7
However sadly...there is a variable mentioned, activeField and i cannot figure out how it is declared. I would really like if some probably advise how/where it is declared or even a solution to scrolling when the keyboard is activated will help.
Thank you

To answer your specific question, since the Apple Documentation is only ever using activeField for size data, you can simply declare it as a private global UIView *activeField and it will work for textFields, textViews, etc all the same.
However, their code actually doesn't work very well at all. I had to make some changes to their code to get mine to work correctly. This code is basically theirs with some minor tweaks to handle all of the cases listed below:
1) If you have a smaller scrollView nested inside of a view, not full screen scrollView and it still works.
2) If you want to move text fields down to the keyboard focus area as well as move them up from behind the keyboard.
3) Works on textViews and textFields of various sizes
4) If the keyboard is currently showing, it will move any newly tapped fields into the focus area
5) Works if you have your content already scrolled and invoke the keyboard
6) Works on all keyboard sizes for all devices (no hardcoded constants)
First off, create private variables for these:
UIView *_activeField;
CGFloat _keyboardHeight;
BOOL _isShowingKeyboard;
Next, just cut and paste this code into your ViewController (it looks like a lot but it's not that bad).
#pragma mark TextFieldKeyboardScrolling
- (void)registerForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)adjustInputFieldsForKeyboard {
CGFloat keyBoardTopInScrollView = self.view.frame.size.height - _keyboardHeight - self.scrollView.frame.origin.y;
CGFloat inputFieldBottomInVisibleScrollView = _activeField.frame.origin.y - self.scrollView.contentOffset.y + 30 /* small buffer for cursor size */;
CGPoint scrollPoint;
if (keyBoardTopInScrollView > inputFieldBottomInVisibleScrollView) {
scrollPoint = CGPointMake(0.0, self.scrollView.contentOffset.y - (keyBoardTopInScrollView - inputFieldBottomInVisibleScrollView));
} else {
scrollPoint = CGPointMake(0.0, self.scrollView.contentOffset.y + (inputFieldBottomInVisibleScrollView - keyBoardTopInScrollView));
}
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
- (void)keyboardWasShown:(NSNotification*)aNotification {
_isShowingKeyboard = YES;
NSDictionary* info = [aNotification userInfo];
_keyboardHeight = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, _keyboardHeight, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
[self adjustInputFieldsForKeyboard];
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
_isShowingKeyboard = NO;
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
_activeField = textField;
if (_isShowingKeyboard) {
[self adjustInputFieldsForKeyboard];
}
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
_activeField = nil;
}
That's it, just call [self registerForKeyboardNotifications]; in your viewDidLoad method, hook up your scrollView outlet and textField/textView delegates in storyboard and you're all set.

The keyboard is only active when one of the texfields become active(Became first responder).So you should listen to UITextField delegate method to see when and which uitextfield became first responder.
- (void)textFieldDidBeginEditing:(UITextField *)textField
if you assign a tag to your textfield or make it ivar you can also understand which uitextfield has become active and also get its frame.

I don't use the scroll view or follow the above documentation.
Here is how without using the scroll view
In my
textFieldShouldBeginEditing
CGRect frame = self.view.frame;
frame.origin.y = <some negative value>;
self.view.frame = frame
and in my
textFieldShouldEndEditing
CGRect frame = self.view.frame;
frame.origin.y = <some positive value>; // absolute value of your above negative value
self.view.frame = frame
The above works for me. Remember these are the text field delegate methods. So you need to setup your delegate.

Related

Adjust static UITableView when keyboard appears?

I am working on a app which contains UITextField and UITextView in static UITableView. I am facing two issues
When I select UITextField it moved correctly but it is not working for UITextView.
When the keyboard disappears the UITableView not shown properly.
All I want is to adjust UITextField and UITextView accordingly when keyboard appears and disappears. Here is my code.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
- (void)keyboardWillShow:(NSNotification *)notification {
//get the end position keyboard frame
NSDictionary *keyInfo = [notification userInfo];
CGRect keyboardFrame = [[keyInfo objectForKey:#"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
//convert it to the same view coords as the tableView it might be occluding
keyboardFrame = [self.tableView convertRect:keyboardFrame fromView:nil];
//calculate if the rects intersect
CGRect intersect = CGRectIntersection(keyboardFrame, self.tableView.bounds);
if (!CGRectIsNull(intersect)) {
//yes they do - adjust the insets on tableview to handle it
//first get the duration of the keyboard appearance animation
NSTimeInterval duration = [[keyInfo objectForKey:#"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
//change the table insets to match - animated to the same duration of the keyboard appearance
[UIView animateWithDuration:duration animations:^{
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, intersect.size.height, 0);
self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, intersect.size.height, 0);
}];
}
}
- (void) keyboardWillHide: (NSNotification *) notification{
NSDictionary *keyInfo = [notification userInfo];
NSTimeInterval duration = [[keyInfo objectForKey:#"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
//clear the table insets - animated to the same duration of the keyboard disappearance
[UIView animateWithDuration:duration animations:^{
self.tableView.contentInset = UIEdgeInsetsZero;
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}];
}
Try with the UITableView's instance method: scrollToRowAtIndexPath:atScrollPosition:animated:
In keyBoardWillShow use the tableview's or the textfield's index path and set the scroll position to UITableViewScrollPositionTop.
If it doesn't work as you want it to, try with scrollToRowAtIndexPath:atScrollPosition:animated:
Hope this helps, good luck! :))
For further information, check out Apple's UITableView reference: https://developer.apple.com/library/ios/documentation/uikit/reference/UITableView_Class/Reference/Reference.html
You can use a third party library for avoiding keyboard scrolling above of text field or text views.
Use https://github.com/cokecoffe/ios-demo/blob/master/TPKeyboardAvoiding/TPKeyboardAvoidingScrollView.m
OR
You can use UITableviewController as your view controller class.Change the Tableview content property to Static. Then you can add any UI controls to the static cells of the table view from story board.
If you select any text field or text view in your tableview, then key board automatically shows below of your text field or text view without any programming logic.

Move view when jumping from text field to text field

I have a form with a few text fields on a scroll view. I was trying to solve the problem of the keyboard hiding some text fields, which I partly did. At least it works well when I tap on each individual field. I used the recommended Apple approach:
I have registered for keyboard notifications in viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:self.view.window];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:self.view.window];
I am tracking active text fields:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
activeTextField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
activeTextField = nil;
}
I am scrolling the view up when the keyboard shows up:
- (void)keyboardWillShow:(NSNotification *)aNotification {
// Get the size of the keyboard
NSDictionary* info = [aNotification userInfo];
keyboardHeight = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardHeight, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
CGRect aRect = self.view.frame;
aRect.size.height -= keyboardHeight + 44 + 44; // Compensates for Navbar and text field height
if (!CGRectContainsPoint(aRect, activeTextField.frame.origin) ) {
[scrollView scrollRectToVisible:activeTextField.frame animated:YES];
}
}
I then scroll the view back to default when the keyboard is hidden (I won't paste the code simply because it works fine).
However, out of my 5 text fields, the first 4 have a Next button on the keyboard (instead or Return) while the last field has Done. The idea is that I want the user to jump from one text field to another (in one direction is enough in my case). So, I've implemented a UITextField delegate method to handle that as well:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == firstNameTextField) {
[lastNameTextField becomeFirstResponder];
} else if (textField == lastNameTextField) {
[countryTextField becomeFirstResponder];
} else if (textField == cityTextField) {
[zipCodeTextField becomeFirstResponder];
} else if (textField == zipCodeTextField) {
[zipCodeTextField resignFirstResponder];
}
return NO;
}
The middle text field above is skipped, because for that text field I'm using a different input type (a custom view with a UIPickerView and a bar on top with Next button) - the missing code is in this method:
- (IBAction)goToNextTextField:(id)sender {
[cityTextField becomeFirstResponder];
}
OK, as I've mentioned, view adjustment works well when tapping individual text fields (and then dismissing the keyboard), even though keyboard sizes (standard iOS vs my custom view) are different heights. I can also successfully go through all text fields tapping on Next buttons.
Here are my issues though:
When tapping on Next, if the keyboard is not changing (say, from field 4 to 5 that both use standard keyboard), my keyboardWillShow: method is not called, NSLog debugger shows keyboardHeight as 0, and yet the view moves up unpredictably.
Also, when navigating to and from field 3 (the one that uses custom input view), keyboardHeight is thus not recalculated. I have tried registering to UIKeyboardDidChangeFrameNotification and UIKeyboardWillChangeFrameNotification (pointing to keyboardWillShow: method), but without much success. It is worth noting that I do see in console that keyboardHeight is changing, but it's usually lagging one step, i.e. keyboardHeight is updated when I leave the field, not when it becomeFirstResponder.
Perhaps a pair of experienced eyes will spot my mistake, for I have been destroying my pair of eyes searching for the solution for the last 2 days..
Thanks!
You can use UITextField delegates . Whenever user start editing in any textfield its delegate is called you can change scrollview offset using
- (void)scrollViewToCenterOfScreen:(UIView *)theView
{
CGFloat viewCenterY = theView.center.y;
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
CGFloat availableHeight = applicationFrame.size.height - 200; // Remove area covered by keyboard
CGFloat y = viewCenterY - availableHeight / 2.0;
if (y < 0)
{
y = 0;
}
[scrollView setContentOffset:CGPointMake(0, y+20) animated:YES];
}
So in TextField delegate you can set
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if([textField isEqual:textfield1])
{
[self scrollViewToCenterOfScreen:textfield1];
}
else if([textField isEqual:textfield2])
{
[self scrollViewToCenterOfScreen:textfield2];
}
return YES;
}
and when user press done or return button you can change offset to (0,0)
[scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
Hope this works for you.
https://github.com/simonbs/BSKeyboardControls
this control can show a toolbar above the keyboard when editing a textfield like this
==========================================
-(void)textFieldDidBeginEditing:(UITextField *)textField {
if (textField == firstNameTextField) {
//move to firstNameTextField
} else if (textField == lastNameTextField) {
//move to lastNameTextField
} else if (textField == cityTextField) {
//move to cityTextField
} else if (textField == zipCodeTextField) {
//move to zipCodeTextField
}
return NO;
}
I have in the end implemented a solution that works well for me. It's a mixture of Apple recommended approach, a couple of solutions found on these forums as well as my own.
First of all, register as UITextFieldDelegate on view controller .h file.
Then in viewDidLoad register for keyboard notifications:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:self.view.window];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:self.view.window];
Don't forget to unregister from them (removeObserver:) in viewDidUnload method as well.
Let your application know which text field is currently active:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
activeTextField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
activeTextField = nil;
}
When your application receives a notification that keyboard will show, it calls this method:
- (void)keyboardWillShow:(NSNotification *)aNotification {
keyboardHeight = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
[scrollView setFrame:CGRectMake(scrollView.frame.origin.x,
scrollView.frame.origin.y,
scrollView.frame.size.width,
scrollView.frame.size.height - keyboardHeight)];
[self moveViewWithKeyboard];
}
All I'm doing here is decreasing the size of my scrollView frame by the size of the keyboard. After that I call my moveViewWithKeyboard: method that will make active view visible.
Interestingly enough, to solve the problem of correct keyboard height being detected one step too late (read my original question above), I had to change the argument UIKeyboardFrameBeginUserInfoKey in keyboard height detection line with UIKeyboardFrameEndUserInfoKey argument. Having done so, keyboard (or custom view) is detected when moving to the relevant field, not when moving away from it.
Of course, I have to restore original view frame when the keyboard hides (and note that I'm still calling the moveViewWithKeyboard: method with nil as an argument):
- (void)keyboardWillHide:(NSNotification *)aNotification {
[scrollView setFrame:CGRectMake(scrollView.frame.origin.x,
scrollView.frame.origin.y,
scrollView.frame.size.width,
scrollView.frame.size.height + keyboardHeight)];
[self moveViewWithKeyboard];
}
I also added calls to move view when keyboard hide/show is not triggered. This happens when I jump from text field to text field that have system keyboard as input, so it is neither hidden nor shown again (and no notifications are issued to trigger delegate methods).
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == firstNameTextField) {
[lastNameTextField becomeFirstResponder];
} else if (textField == lastNameTextField) {
[countryTextField becomeFirstResponder];
} else if (textField == cityTextField) {
[zipCodeTextField becomeFirstResponder];
} else if (textField == zipCodeTextField) {
[zipCodeTextField resignFirstResponder];
}
[self moveViewWithKeyboard:nil];
return NO;
}
And finally my method to move view:
- (void)moveViewWithKeyboard {
if (activeTextField) {
[scrollView scrollRectToVisible:activeTextField.frame animated:YES];
} else {
[scrollView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}
}
Note that when no text field is passed as an argument (i.e. no text field is active), view is scrolled to its original position.
Hope this helps someone.

Scrolling view when keyboard appears: Library or DIY?

I've had it up to my neck trying to make the whole view moving to the appropriate UITextField when a user taps on a respective object look seamless. I know that I'm not the only one that absolutely hates doing this too.
What is the best approach to making this work as beautifully as possible with the least amount of work possible?
I've tried out TPKeyboardAvoiding, and it totally sucked.
Right now, I've got this code going, but it sucks as well in it's own special way:
- (void)viewDidLoad
{
self.view.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin);
self.scrollView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin);
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWasShown:(NSNotification *)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, self.activeField.frame.origin) ) {
CGPoint scrollPoint = CGPointMake(0.0, self.activeField.frame.origin.y-kbSize.height);
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
- (void)keyboardWillBeHidden:(NSNotification *)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
For me, it works TPKeyboardAvoiding , I use it in all my projects. Have you tried to:
Add a UIScrollView into your view controller's xib
Set the scroll view's class to TPKeyboardAvoidingScrollView (still
in the xib, via the identity inspector)
Place all your controls within that scrollview ?
I also find this solution :Keyboard Manager
Download demo project
Just drag and drop KeyboardManager and SegmenedNextPrevious classes to your project
In your appDelegate write only one line of code:
[KeyBoardManager installKeyboardManager];
Good luck!
Did you know that if your view controller derives from UITableViewController, scrolling the table view is automatic when the keyboard displays when a text field or text view gets focus? You don't have to do anything. That being said, it may not work well for your app to refactor the UI so that it uses a table view with static cells instead of whatever you're doing now, though.
If this wont work for you, you can change your scroll view's contenSize to be the size of your visible area when the keyboard is shown and then call scrollRectToVisible:animated: on your scroll view passing it the rect of your textfield inside of your keyboardWasShown: selector.

Problem with scrollview, it scrolls more

I have a scrollView and i want to scroll it automatically when i select an textField
(i am filling a form here)
i am using following method to scroll it
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[scrollView setContentOffset:CGPointMake(0,50*(textField.tag-1))];
}
Now the problem is that i have more than 10 text fields and when i reached to the seventh textField the scrollView scrolls more .
I also tried to print the CGPointMake()'s values...and it is showing correct values..but the scroller goes beyond the range what is expected..
Look at following images
The following 2 images showing control on textFields tag <7
But when control reaches to 7th textField it scrolls more
and after this it goes beyond bounds.
This problem occurs only when i move from one textFields to another without pressing that return button(i mean with resignFirstResponder).But when i press that return button and then go to the next field then all works fine.
Can anyone suggest where should be the problem..?
It won't scroll because it doesn't contain enough content. It will stop when the bottom edge of the content reaches the bottom end of the frame. Use something like
CGSize size = scrollView.contentSize;
scrollView.contentSize = CGSizeMake (size.width, size.height + ADDITIONAL_HEIGHT);
when setting up the scroll view, or in your -viewDidLoad: method, if it was loaded from a XIB.
It should keep the text field being edited on the screen - i.e. scroll automatically - so you shouldn't need to do anything?
However, it might be trying to edit a text field that is behind the keyboard - so the better solution would be:
//Get notifications of the keyboard opening and closing
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
- (void)keyboardWillShow:(NSNotification *)notification {
//Get the keyboard height
int h = [self.view convertRect:[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] toView:nil].size.height;
//Change the inset of the scroll view and scroll bars
scrollView.contentInset = scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, h, 0);
}
- (void)keyboardWillHide:(NSNotification *)notification {
scrollView.contentInset = scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, 0);
}
try this.declare a variable
CGPoint svos;
in .h file and do this.
- (void)textFieldDidBeginEditing:(UITextField *)textField {
svos = scr.contentOffset;//scr is my scroll view
CGPoint pt;
CGRect rc = [textField bounds];
rc = [textField convertRect:rc toView:scr];
pt = rc.origin;
pt.x = 0;
pt.y -= 60;
[scr setContentOffset:pt animated:YES];
//NSLog(#"%f",pt.y);
}

How to get a reference to a method's caller object from within the method in Objective-C

I have a few text fields and text views on my application's view. The keyboard comes up when I click in anyone of them. I have a method that gets called when any one of these objects is tapped in. However, I would like the method to execute its code only if the a certain Text Field(s) or a certain Text View(s) is tapped in. I would therefore like to have something like this in the method body:
{
if(currentField != mySpecialField)
{return;}
//Rest of the method code...
}
Now, my question is, how do I get a reference to the currently tapped in field so that I can perform the if-check.
Update:
In my situation, I am using the code I got from Apple's website that makes use of these methods:
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
if (keyboardShown)
return;
NSDictionary* info = [aNotification userInfo];
// Get the size of the keyboard.
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
// Resize the scroll view (which is the root view of the window)
CGRect viewFrame = [scroller frame];
viewFrame.size.height -= keyboardSize.height;
scroller.frame = viewFrame;
// Scroll the active text field into view.
CGRect textFieldRect = [activeField frame];
[scroller scrollRectToVisible:textFieldRect animated:YES];
keyboardShown = YES;
}
// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
// Get the size of the keyboard.
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
// Reset the height of the scroll view to its original value
CGRect viewFrame = [scroller frame];
viewFrame.size.height += keyboardSize.height;
scroller.frame = viewFrame;
keyboardShown = NO;
}
Can I modify these methods in such a way that I can get a reference to the caller UITextField and / or the caller UITextView?
Update:
Here's the method that's used for registration:
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotification object:nil];
}
Is there any way I can achieve what I'm trying to achieve? Maybe if I modify the code above to pass 'object:self' instead of 'object:nil'?
Controls that are subclasses of UIControl (for example UIButton or UITextField) automatically sends a reference to themselves along to their target.
When creating your text fields, just specify a selector that takes one argument. In this example, "myTextField" is an instance variable:
myTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
[myTextField addTarget:self action:#selector(textFieldTapped:) forControlEvents:UIControlEventTouchUpInside];
And then the method we specified, textFieldTapped:, to handle the event:
- (void)textFieldTapped:(UITextField *)sender {
// Ignore any events that doesn't come from myTextField
if (sender != myTextField) return;
// TODO: Do stuff
}
In the case of UITextField you can also check out the UITextFieldDelegate protocol (the "delegate" value of your text field). It sends out various events that can be used to register the same kind of things, for example:
- (void)textFieldDidBeginEditing:(UITextField *)textField