【问题标题】:Scroll UITableView up when keyboard appears in swift [duplicate]当键盘出现在swift中时向上滚动UITableView [重复]
【发布时间】:2016-03-22 19:46:17
【问题描述】:

我有一个UITableView,有 7 个单元格,每个单元格里面都有一个文本字段。当键盘出现时,它会隐藏最后一个单元格,因此很难看到输入的内容,除非键盘消失。

谁能指导我如何在键盘出现时向上滚动这个UITableview,这样我就没有这个问题了?

【问题讨论】:

  • 一个tableview只是一个UIScrollView的子类,可以使用官方文档中提供的答案developer.apple.com/library/ios/documentation/StringsTextFonts/…
  • 这是在 Objective-c 中。我现在有一个 swift 版本,如果将来有人需要它。 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWasShown:"), name:UIKeyboardDidShowNotification, object: nil); NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
  • 然后函数体是这样的:func keyboardWasShown(sender: NSNotification) { let info:NSDictionary = sender.userInfo!让 kbSize:CGSize = (info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size)!让 contentInsets:UIEdgeInsets = UIEdgeInsetsMake(0.0,0.0,kbSize.height,0.0) tableView.contentInset = contentInsets tableView.scrollIndicatorInsets = contentInsets }
  • func keyboardWillHide(sender: NSNotification) { let contentInsets:UIEdgeInsets = UIEdgeInsetsZero; tableView.contentInset = contentInsets; tableView.scrollIndicatorInsets = contentInsets; }
  • 最好的解决方案是您可以在这里找到:github.com/michaeltyson/TPKeyboardAvoiding

标签: ios swift uitableview keyboard


【解决方案1】:

使用这组简单的类https://github.com/michaeltyson/TPKeyboardAvoiding

使用方法:

要与UITableViewController 类一起使用,请将 TPKeyboardAvoidingTableView.m 和 TPKeyboardAvoidingTableView.h 放入您的项目中,并将您的 UITableView 设置为 xib 中的 TPKeyboardAvoidingTableView。如果您没有在控制器中使用 xib,我知道没有简单的方法使其 UITableView 成为自定义类:阻力最小的路径是为其创建 xib。

【讨论】:

    【解决方案2】:

    试试这个:

    func textFieldDidBeginEditing(textField: UITextField) {
        tableView.setContentOffset(CGPointMake(0, textField.center.y-60), animated: true)
    }
    

    【讨论】:

    • 有趣的想法,但在所有可能的情况下都无法正常工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2014-12-09
    • 2014-02-07
    相关资源
    最近更新 更多