UITableView滚动/插入问题

时间:2017-10-11 06:15:49

标签: ios swift

我有一个带有多个文本字段的UITableView。当我单击文本字段时,我将setContentOffset将文本字段放到页面顶部,但是当键盘出现时我没有足够的插页。所以我在视图的底部添加了插页。这允许我一直向下滚动,但现在当我选择一个字段时,它向下滚动太远,比我设置的setContentOffset更远。我尝试了不同的内容插入值,但没有一个工作。有没有办法解决这个内容插入问题?

func adjustInsetForKeyboardShow(_ show: Bool, notification: Notification) {
        if !keyboardAdjusted || !show {
            guard let value = (notification as NSNotification).userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else { return }
            let keyboardFrame = value.cgRectValue
            var adjustmentHeight = (keyboardFrame.height + 100) * (show ? 1 : -1)
            adjustmentHeight = (adjustmentHeight < 0.0) ? 0.0 : adjustmentHeight

            self.editPaymentTableView.contentInset.bottom = adjustmentHeight
            self.editPaymentTableView.scrollIndicatorInsets.bottom = adjustmentHeight
        }
        keyboardAdjusted = show
    }

1 个答案:

答案 0 :(得分:1)

我已经在SO上找到了这个,但是找不到它的链接了,这里的代码非常巧妙地处理了键盘和tableview的插图。好的是它是为了展示和隐藏。无需实现其他键盘通知:

public func keyboardWillChangeFrame(notification: NSNotification) {
    guard
        let userInfo = notification.userInfo,
        let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
        let duration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
        let animationCurveRawNSNumber = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
        else {
            return
    }

    let animationCurveRaw = animationCurveRawNSNumber.uintValue
    let animationCurve: UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)

    let offsetY: CGFloat
    if endFrame.origin.y >= UIScreen.main.bounds.size.height {
        offsetY = 0.0
    } else {
        offsetY = endFrame.size.height
    }

    let contentInsets = UIEdgeInsetsMake(0, 0, offsetY, 0)
    UIView.animate(withDuration: duration, delay: TimeInterval(0), options: animationCurve, animations: {
        self.tableView.contentInset = contentInsets
        self.tableView.scrollIndicatorInsets = contentInsets
    }, completion: nil)
}

就您的解决方案而言,您可以替换这两行:

var adjustmentHeight = (keyboardFrame.height + 100) * (show ? 1 : -1)
adjustmentHeight = (adjustmentHeight < 0.0) ? 0.0 : adjustmentHeight

使用:

var adjustmentHeight = keyboardFrame.height * (show ? 1 : 0)

并确保你也将顶部插图设为0:

let contentInsets = UIEdgeInsetsMake(0, 0, adjustmentHeight, 0)
self.editPaymentTableView.contentInset = contentInsets