我认为我有两个文本文件。按下文本字段时,从底部显示 UIPickerView 或普通键盘(取决于文本文件的类型)。UIScrollView 包装了我视图中的所有内容。
ViewController.h 文件如下所示:
@interface MyViewController : UIViewController<UIPickerViewDataSource, UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UITextField *textNormal;
@property (weak, nonatomic) IBOutlet UITextField *textScroll;
@property UIPickerView * picker;
@end
我混合了一些代码来滚动到滚动视图,以便在显示键盘或选择器视图时使文本字段可见。
ViewController.m 文件:
@interface MyViewController ()
@property BOOL keyboardVisable;
@property CGPoint offset;
@property CGRect frame;
@property UIPickerView * picker;
@end
@implementation MyViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.keyboardVisable = NO;
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
tapGesture.cancelsTouchesInView = NO;
[self.scrollView addGestureRecognizer:tapGesture];
self.picker = [[UIPickerView alloc] init];
self.textScroll.inputView = self.picker;
self.picker.delegate = self;
self.picker.dataSource = self;
self.picker.showsSelectionIndicator = YES;
}
-(void)hideKeyboard
{
NSLog(@"hide now");
[self.scrollView endEditing:YES];
}
- (void)keyboardDidShow:(NSNotification *)notif{
if(self.keyboardVisable)
return;
NSLog(@"keyboard did show");
NSDictionary* info = [notif userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
// Save the current location so we can restore
// when keyboard is dismissed
self.offset = self.scrollView.contentOffset;
self.frame = self.scrollView.frame;
// Resize the scroll view to make room for the keyboard
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height -= keyboardSize.height;
self.scrollView.frame = viewFrame;
CGRect textFieldRect = [self.textScroll frame];
textFieldRect.origin.y += 10;
[self.scrollView scrollRectToVisible:textFieldRect animated:YES];
// Keyboard is now visible
self.keyboardVisable = YES;
}
- (void)keyboardDidHide:(NSNotification *)notif{
if(!self.keyboardVisable)
return;
NSLog(@"keyboard did hide");
//self.scrollView.contentOffset = self.offset;
self.scrollView.frame = self.frame;
[self.scrollView setContentOffset:self.offset animated:YES];
self.keyboardVisable = NO;
}
当按下普通文本字段时,这些代码正常工作。
(滚动视图会改变它的框架大小和偏移量,以使文本字段可见,并且当按下键盘以外的任何地方都会恢复正常)
但是,它们不适用于带有 inputView == pickerview 的文本字段。滚动视图会按预期改变它的帧大小。一旦用户滚动了pickerview,背景(scrollview)将突然滚动到顶部并意外变为不可滚动。
谢谢!