UITableView自定义单元格轻触文本字段时自动滚动:Swift 3

时间:2018-02-22 07:59:11

标签: ios swift uitableview swift3

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

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

请在下面找到图片:

enter image description here

2 个答案:

答案 0 :(得分:2)

无需任何计算,使用下面的代码就能完美运行,

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)
    }
}

答案 1 :(得分:1)

API的Swift 4.2有所更改。您需要执行与此类似的操作。

//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)
}