ios开发中,键盘会自动遮挡UITextFiled,用户友好性差,下面有几种解决的办法。
1、界面中底部使用的UIView,然后在上面放入的界面。将下面的代码加入即可。
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField: textField up: YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self animateTextField: textField up: NO];
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
const int movementDistance = 80; // tweak as needed
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
完成后需要为自己的类设置文本代理。
@interface EVLoginController : UIViewController<MBProgressHUDDelegate,UITextFieldDelegate>
给需要上浮的文本框加上代理事件。
//输入框添加输入上浮事件
txtUserphone.delegate = self;
txtUserPassword.delegate = self;
2、参考stackoverflow中提出的方法。
http://stackoverflow.com/questions/1126726/how-to-make-a-uitextfield-move-up-when-keyboard-is-present?page=1&tab=votes#tab-top
苹果的解决方案,需要使用UIScrollView
https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW1
里面使用了git中通用的解决方案。
https://github.com/michaeltyson/TPKeyboardAvoiding (UIScrollView based)
https://github.com/kirpichenko/EKKeyboardAvoiding (UIScrollView based)
https://github.com/robbdimitrov/RDVKeyboardAvoiding (UIScrollViewbased)
https://github.com/hackiftekhar/IQKeyboardManager (looks interesting)
https://github.com/danielamitay/DAKeyboardControl (looks interesting)
https://github.com/IdleHandsApps/IHKeyboardAvoiding
3、使用IQKeyBoardManager,如果使用object-c,直接使用pod将文件加入进来就可以使用,不需要做任何的配置。详细可以参考文档。IQKeyBoardManager功能比较多,可能与第三方库冲突,但是毫无侵入性,建议使用。其次看IHKeyBoardAvoiding比较轻量级,可以尝试去使用。