Reputation: 941
I have 3 text-fields and 2 buttons. When I tap on text-field, keyboard comes up and the 2 buttons are hidden because of the keyboard. Is it possible to move the buttons above the keyboard and when the keyboard resigns the buttons should go back to their initial position.
Upvotes: 0
Views: 1955
Reputation: 1181
The best way to do this is use library, here is the link https://github.com/michaeltyson/TPKeyboardAvoiding, all you need to do is take all your textfields and buttons in UIScrollView and assign scrollview class as "TPKeyboardAvoidingScrollView" in storyboard.
There will be zero lines of code in view controller class to manage your requirement and wherever you want to do this throughout your app you can similarly.
Upvotes: 0
Reputation: 5172
Better go with scrollview or else adapt the code below for your convenience.
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: "tap:")
view.addGestureRecognizer(tapGesture)
self.txtUserEmail.delegate = self;
self.txtPassword.delegate = self;
}
func tap(gesture: UITapGestureRecognizer) {
self.txtUserEmail.resignFirstResponder()
self.txtPassword.resignFirstResponder()
}
Upvotes: -1
Reputation: 1324
//Declare a delegate, assign your textField to the delegate and then
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
[self.view endEditing:YES];
return YES;
}
- (void)keyboardDidShow:(NSNotification *)notification
{
// Assign new frame to your view
[self.view setFrame:CGRectMake(0,-110,320,460)]; //here taken -20 for example i.e. your view will be scrolled to -20. change its value according to your requirement.
}
-(void)keyboardDidHide:(NSNotification *)notification
{
[self.view setFrame:CGRectMake(0,0,320,460)];
}
Edit :- Assign width and height to View using [UIScreen mainScreen] bounds].size
Upvotes: 4
Reputation: 1266
Yes, you can update the View frames/constraints so buttons will get shown to user.
Moreover you can create a toolbar which will be having those buttons in it. You can add toolbar above the keyboard when textfields are focused.
It will be a better user experience.
Upvotes: -1