簡體   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