出现UITextView键盘时滚动tableview

时间:2018-11-18 14:08:53

标签: ios swift uitableview uiscrollview uitextview

我知道这是一个经常被问到的问题,但是我无法获得任何已发布的解决方案(例如here)以适合我的情况。首先,当我使用

处理keyboardWillShow通知时
  if let keyboardHeight = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height {
            tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
        }

什么都没有发生。似乎有点hack,但是下面的此实现(特别是在keyboardWillShow中)对我有用,但是奇怪的是(1)第一次不起作用,但以后每次都起作用(2)上方出现一个大的白条键盘由于某种原因?我认为这并不重要,但是我的UI允许用户点击“编辑”按钮,以便他们可以看到可编辑的内容,然后编辑textView,然后点击“完成”。我要解决的问题是此textView位于tableView的底部,因此键盘在编辑时会将其遮盖。

class ScoreAndStatsViewController: UITableViewController, UITextFieldDelegate, UITextViewDelegate   {

    @IBOutlet weak var editButton: UIButton!
    @IBOutlet weak var notesTextField: UITextView!


    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIApplication.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIApplication.keyboardWillHideNotification, object: nil)

    }

 @IBAction func editButtonIsPressed(_ sender: UIButton) {

        if editMode == false {

        notesTextField.isEditable = true

        notesTextField.backgroundColor = iPhoneForeGroundColor


        editButton.setTitle("Done", for: .normal)

        self.editMode = true

        //If edit mode is true, this means they've hit the done button so save
        } else {

            //save data 

            editButton.setTitle("Edit", for: .normal)
            notesTextField.isEditable = false



            notesTextField.backgroundColor = UIColor.clear

            self.editMode = false 


        }
    }



// MARK: Keyboard Notifications

    @objc func keyboardWillShow(notification: NSNotification) {

        let pointInTable:CGPoint = notesTextField.superview!.convert(notesTextField.frame.origin, to: tableView)
        var contentOffset:CGPoint = tableView.contentOffset
        contentOffset.y  = pointInTable.y
        if let accessoryView = tableView.inputAccessoryView {
            contentOffset.y -= accessoryView.frame.size.height
        }
        tableView.contentOffset = contentOffset
    }

    @objc func keyboardWillHide(notification: NSNotification) {
        UIView.animate(withDuration: 0.2, animations: {
            // For some reason adding inset in keyboardWillShow is animated by itself but removing is not, that's why we have to use animateWithDuration here
            self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        })
    }
}

0 个答案:

没有答案
相关问题