【问题标题】:UITableView Custom Cell Auto scroll when text field is tapped : Swift 3点击文本字段时UITableView自定义单元格自动滚动:Swift 3
【发布时间】:2018-08-01 23:59:24
【问题描述】:

这里我使用了自定义UITableviewCell,每个单元格都有多个UITextfield,它看起来像Cardview

当我点击添加图标时,将添加新的 Cardview。 这里我不知道当我们点击 UITextfield 时如何处理 Autoscroll 选项。

请在下面找到图片:

【问题讨论】:

标签: ios swift uitableview swift3


【解决方案1】:

无需任何计算,使用以下代码即可完美运行,

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

 func keyboardWillShow(_ notification:Notification) {

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        reimbursementTableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
    }
}

func keyboardWillHide(_ notification:Notification) {

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        reimbursementTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
    }
}

【讨论】:

    【解决方案2】:

    Swift 4.2 的 API 发生了一些变化。你需要做类似的事情。

    //inside viewDidLoad
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
    

    然后我们将不得不支持功能。由于我们涉及选择器(这是 Objective C 的一部分),我们需要在函数中使用 @objc 前缀。

    @objc func keyboardWillShow(_ notification:Notification) {
    
            if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
                tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
            }
    }
    
    @objc func keyboardWillHide(_ notification:Notification) {
    
            if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
                tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            }
    }
    

    如果您的 UITableView 有不同的名称,请更改函数内的变量 tableView

    另外,如果您想在用户触摸 TextView 或 TextField 外部时隐藏键盘,请执行以下操作。

    //inside the viewDidLoad
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
    view.addGestureRecognizer(tap)
    

    并实现如下选择器中给出的功能

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多