簡體   English   中英

UITableView自定義單元格輕觸文本字段時自動滾動:Swift 3

[英]UITableView Custom Cell Auto scroll when text field is tapped : Swift 3

在這里,我使用Custom UITableviewCell ,每個單元格都有多個UITextfield ,看起來像Cardview

當我點擊添加圖標時,將添加新的Cardview。 在點擊UITextfield時,我不知道如何處理Autoscroll選項。

請在下面找到圖片:

在此輸入圖像描述

無需任何計算,使用下面的代碼它將完美地工作,

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM