键入时扩大uitableview单元格的高度,并避免使用键盘

时间:2018-10-16 06:15:35

标签: swift uitableview

我有一个带textview的tableview。我想在键入时以及ui键盘隐藏uitexview滚动表时根据uitextview的内容设置tableviewcell的高度。

下面是根据内容扩展单元格高度的代码

func updateCellHeight(indexPath: NSIndexPath, comment: String,textview: UITextView) {

    let tempDict = arrayTexts[indexPath.row] as! NSMutableDictionary
    tempDict.setValue(comment, forKey: "content")
    arrayTexts[indexPath.row] = tempDict
    self.tblFields.beginUpdates()
    self.tblFields.endUpdates()


}

上面的代码有效,但不能避免使用键盘

以下代码用于避免键盘输入

func textviewBeginEditing(textview: UITextView) {
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)

    self.tblFields.contentInset = contentInsets
    self.tblFields.scrollIndicatorInsets = contentInsets

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    var aRect = self.view.frame
    aRect.size.height -= keyboardHeight

    if !aRect.contains(textview.frame.origin) {
        self.tblFields.scrollRectToVisible(textview.frame, animated: false)
    }

}

上面的代码有时避开键盘,有时不避开键盘,但是tableview在键入时不断滚动,并且无法正常工作。我怎么了?

1 个答案:

答案 0 :(得分:0)

从textviewBeginEditing函数中删除代码,并添加以下代码

func updateCellHeight(indexPath: NSIndexPath, comment: String, textview: UITextView) {

    let tempDict = arrayTexts[indexPath.row] as! NSMutableDictionary
    tempDict.setValue(comment, forKey: "value")
    arrayTexts[indexPath.row] = tempDict

    if textview.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height != textview.frame.size.height {

        UIView.setAnimationsEnabled(false)
        self.tblFields.beginUpdates()
        self.tblFields.endUpdates()
        UIView.setAnimationsEnabled(true)

    }

}