Move UIButton above Keyboard when tapped on UITextField

浪尽此生 提交于 2019-12-01 13:19:34

问题


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.


回答1:


//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




回答2:


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.




回答3:


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.




回答4:


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()
    }


来源:https://stackoverflow.com/questions/35909394/move-uibutton-above-keyboard-when-tapped-on-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!