我的观点中有两个文本。按下文本字段时,从底部显示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的文本字段上工作。 scrollview会按预期更改其帧大小。一旦用户滚动了选择器视图,背景(scrollview)将突然滚动到顶部并意外地变为不可滚动。
谢谢!