【发布时间】:2018-03-08 18:51:34
【问题描述】:
我已经构建了一个自定义 UIView,并将其添加到 UIViewController。
我希望我的自定义 UIView 向上移动以显示键盘隐藏的任何文本字段。但是,它似乎只是将 UIView 的其他元素向上推。
我做错了什么? 没有键盘:
注意当显示键盘时日期和公司名称是如何被推到UITextFields 后面的
LogInViewController.m
@interface LogInViewController () <UITextFieldDelegate> {
LoginView * loginView;
}
@property (nonatomic, assign) CGRect keyboardFrame;
@end
- (void)viewDidLoad {
[super viewDidLoad];
loginView = [[LoginView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:loginView];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[nc addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)handleKeyboardDidShow:(NSNotification *)notification {
NSTimeInterval animationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
_keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
_keyboardFrame = [self.view convertRect:_keyboardFrame fromView:self.view.window];
[UIView animateWithDuration:animationDuration animations:^{
CGRect frm = loginView.frame;
frm.size.height = CGRectGetMinY(_keyboardFrame);
loginView.frame = frm;
}];
}
- (void)handleKeyboardWillHide:(NSNotification *)notification {
NSTimeInterval animationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
[UIView animateWithDuration:animationDuration animations:^{
CGRect frm = loginView.frame;
frm.size.height = CGRectGetMaxY(self.view.bounds);
loginView.frame = frm;
}];
}
LoginView.h
@interface LoginView : UIView
@property (strong, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UITextField *txtUsername;
@property (weak, nonatomic) IBOutlet UITextField *txtPassword;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *indicator;
@property (weak, nonatomic) IBOutlet UIButton *btnSignin;
@property (weak, nonatomic) IBOutlet UILabel *lblVersion;
@property (weak, nonatomic) IBOutlet UILabel *lblMessageArea;
@end
LoginView.m
@implementation LoginView
- (instancetype) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self){
[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
[self addSubview:self.contentView];
self.contentView.frame = self.bounds;
}
return self;
}
@end
【问题讨论】:
-
使用 IQKeyboard 库
标签: ios objective-c uiview uiviewcontroller uikeyboard