【问题标题】:Scroll up tableView when opening the keyboard打开键盘时向上滚动tableView
【发布时间】:2016-12-17 07:12:12
【问题描述】:

我有一个带有一些自定义单元格的 UITable,在最后一个单元格上我有一个 UITextField,我希望所有单元格在打开键盘时都会向上滚动(所有类型的键盘,启用和禁用“预测” )。

我已经查看了有关此主题的其他问题并尝试了,但仍然不够好(单元格与键盘之间存在间隙,tableView 的动画与键盘不同步等...)。

你能帮帮我吗?

谢谢!

【问题讨论】:

标签: ios swift uitableview cocoa-touch


【解决方案1】:

查看Github 上的 iOS Firechat 示例项目。它使用 tableView 外部的文本字段,并在视图出现/消失时随键盘一起移动视图。

特别是本节:

// Setup keyboard handlers to slide the view containing the table view and
// text field upwards when the keyboard shows, and downwards when it hides.
- (void)keyboardWillShow:(NSNotification*)notification
{
    [self moveView:[notification userInfo] up:YES];
}

- (void)keyboardWillHide:(NSNotification*)notification
{
    [self moveView:[notification userInfo] up:NO];
}

- (void)moveView:(NSDictionary*)userInfo up:(BOOL)up
{
    CGRect keyboardEndFrame;
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]
     getValue:&keyboardEndFrame];

    UIViewAnimationCurve animationCurve;
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey]
     getValue:&animationCurve];

    NSTimeInterval animationDuration;
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]
     getValue:&animationDuration];

    // Get the correct keyboard size to we slide the right amount.
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];

    CGRect keyboardFrame = [self.view convertRect:keyboardEndFrame toView:nil];
    int y = keyboardFrame.size.height * (up ? -1 : 1);
    self.view.frame = CGRectOffset(self.view.frame, 0, y);

    [UIView commitAnimations];
}

在 Swift 中也是如此,未经测试:

func moveView(userInfo : NSDictionary, up : Bool){

        var keyboardEndFrame : CGRect?
        userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)?.getValue(&keyboardEndFrame)

        var animationCurve : UIViewAnimationCurve?
        userInfo.objectForKey(UIKeyboardAnimationCurveUserInfoKey)?.getValue(&animationCurve)

        var animationDuration : NSTimeInterval?
        userInfo.objectForKey(UIKeyboardAnimationDurationUserInfoKey)?.getValue(&animationDuration)

        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.setAnimationDuration(animationDuration!)
        UIView.setAnimationCurve(animationCurve!)

        let keyboardFrame = self.view.convertRect(keyboardEndFrame!, toView: nil)

        let y = keyboardFrame.size.height * (up ? -1 : 1);
        self.view.frame = CGRectOffset(self.view.frame, 0, y);

        UIView.commitAnimations()
    }

【讨论】:

  • FS.O5 如果您需要 swift,请删除问题中的 Objective-c 标签。
猜你喜欢
  • 2022-10-09
  • 2017-08-06
  • 2018-05-08
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 1970-01-01
相关资源
最近更新 更多