iOSView程序员iOS移动开发

UIScrollView中UITextView键盘显示、隐藏的问

2015-07-19  本文已影响2287人  alvin_ding

问题1:

由于UITextView作为UIScrollView的子控件,使用常规的收起键盘的方法在这里就会行不通。我尝试了重写touchesBegan方法,点击空白没响应,因为我实际上点的是scrollView。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
} 

解决方案:

在Scroll View 和 Text View之间添加一层View, 将View的class设置为UIControl, 为其Touch Down事件添加相应方法:
- (IBAction)viewTouchDown:(id)sender {
[self.view endEditing:YES];
}

问题2:

显示键盘的时候,键盘会遮挡UITextView, 我想要的效果是,显示键盘的时候,可以通过scrollView的滚动条滚动显示出整个UITextView。

解决方案:

在显示和隐藏键盘的时候添加监听事件,在监听方法中调整scrollView的Frame。

- (void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHidden:) name:UIKeyboardDidHideNotification object:nil];
}
- (void)keyBoardDidShow:(NSNotification *)notification {
    //获取键盘高度
    NSValue *value = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;

    CGRect scrollViewFrame = self.scrollView.frame;
    scrollViewFrame.size.height = self.scrollView.bounds.size.height - keyboardSize.height;
    self.scrollView.frame = scrollViewFrame;
}

- (void)keyBoardDidHidden:(NSNotification *)notification {
    //获取键盘高度
    NSValue *value = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;

    CGRect scrollViewFrame = self.scrollView.frame;
    scrollViewFrame.size.height = self.scrollView.bounds.size.height + keyboardSize.height;
    self.scrollView.frame = scrollViewFrame;
}
上一篇 下一篇

猜你喜欢

热点阅读