繁体   English   中英

如何在swift 4中滚动到tableView的顶部?

[英]How to scroll to the top of the tableView in swift 4?

我的代码确实滚动到 tableView 视图的顶部,但我选择了一行并推送到另一个 ViewController,然后返回并点击标签栏图标它不会滚动到顶部。 它在某种程度上向上滚动但无法正常工作

扩展 UIViewController {

func scrollToTop() {
    func scrollToTop(view: UIView?) {
        guard let view = view else { return }

        switch view {
        case let scrollView as UIScrollView:
            if scrollView.scrollsToTop == true {
                if scrollView.contentOffset.y < -100 {
                    return
                }
                scrollView.setContentOffset(CGPoint(x: 0.0, y: -150), animated: true)
                return
            }
        default:
            break
        }

        for subView in view.subviews {
            scrollToTop(view: subView)
        }
    }

    scrollToTop(view: view)
}


var isScrolledToTop: Bool {
    if self is PaymentsTabController {
        return true
    }
    if self is UITableViewController {
        return (self as! UITableViewController).tableView.contentOffset.y == 0
    }
    for subView in view.subviews {
        if let scrollView = subView as? UIScrollView {
            return (scrollView.contentOffset.y == 0)
        }
    }
    return true
}

}

扩展 MainTabBar: UITabBarControllerDelegate {

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    guard let viewControllers = viewControllers else { return false }
    if viewController == viewControllers[selectedIndex] {
        if let nav = viewController as? UINavigationController {
            guard let topController = nav.viewControllers.last else { return true }
            if !topController.isScrolledToTop {
                topController.scrollToTop()
                return false
            } else {
                nav.popViewController(animated: true)
            }
            return true
        }
    }
    return true
}

}

对于 swift4 尝试 -

scrollView.setContentOffset(.zero, animated: true)

代替

scrollView.setContentOffset(CGPoint(x: 0.0, y: -150), animated: true)

尝试这个!

tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .bottom, animated: true)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM