繁体   English   中英

双击栏按钮项目滚动到顶部

[英]Double tap bar button item to scroll to the top

当我双击任何BarButtonItem时,我想滚动到顶部。 我在 stackOverflow 上看到了很多答案,但没有一个对我有用。 也许我用错了? 我应该将代码放在AppDelegateTableViewControllers的什么位置我想专门添加此功能?

无论如何,我正在使用 Swift 2.3 和 Xcode 8 并且很想得到一些帮助。

谢谢你。

你知道scrollsToTop吗? 我认为这就是您所需要的。 iOS SDK中与UIScrollView scrollsToTop属性相关的描述:

当用户点击状态栏时,最接近状态栏的触摸下方的滚动视图将滚动到顶部,但只有当其scrollsToTop属性为YES时,其委托才会从shouldScrollViewScrollToTop返回NO,并且尚未在顶部。 //在iPhone上,只有在屏幕上有一个scrollsToTop == YES的滚动视图时,我们才执行此手势。 如果找到多个,则不会滚动。

首先设置UITabBarControllerDelegate委托。 可以通过Storyboard轻松设置委托,也可以使用UITabBarController的委托属性通过代码轻松设置。

myTabBar.delegate = myNewDelegate // Have to conform to UITabBarControllerDelegate protocol

您甚至可以子类化UITabBarController并为其实现UITabBarControllerDelegate,以便它可以成为其自身的委托。

mySubclassedTabBar.delegate = mySubclassedTabBar

当您有委托时,您可以尝试这种方法。

func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool
{
    guard let tabBarControllers = tabBarController.viewControllers
    else
    {
        // TabBar have no configured controllers
        return true
    }

    if let newIndex = tabBarControllers.indexOf(viewController) where newIndex == tabBarController.selectedIndex
    {
        // Index won't change so we can scroll

        guard let tableViewController = viewController as? UITableViewController // Or any other condition
        else
        {
            // We are not in UITableViewController
            return true
        }

        tableViewController.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .Top, animated: true)
    }

    return true
}
 func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    if tabBarController.viewControllers!.firstIndex(of: viewController) == 0 {
        if self.selectedIndex != 0 { return true }

        if let navigationController = viewController as? UINavigationController{
            if let streamController = navigationController.viewControllers.last as? HomeVC
            {
                streamController.tableView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)

            }
        }
        return true
    }
    return true
}

暂无
暂无

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

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