扩展UIScrollViewDelegate并使所有viewControllers符合要求?

时间:2016-07-12 00:19:02

标签: swift generics uiviewcontroller uiscrollview swift2

我有一个包含childViewController的parentViewController。 childViewController有一个UICollectionView。我想观察滚动并使其符合另一个与parentViewController对话的协议。如果我在UICollectionViewDelegate中调用该方法,我可以让它为滚动工作,但我希望能够跨任何符合其中包含scrollView的委托的通用ViewController。这可能吗?

以下代码:

protocol HomeScrollDelegate: UIScrollViewDelegate {
    func showButtons()
    func hideButtons()
    weak var homeScrollDelegate: HomeScrollDelegate? { get set }
}

extension HomeScrollDelegate {
    func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        if targetContentOffset.memory.y > scrollView.contentOffset.y {
            homeScrollDelegate?.hideButtons()
        } else {
            homeScrollDelegate?.showButtons()
        }
    }
}

class HomeCollectionViewController: UIViewController {
    weak var homeDelegate: HomeScrollDelegate?
    etc etc
}

extension HomeCollectionViewController: UICollectionViewDelegate {
    weak var homeScrollDelegate: HomeScrollDelegate? {
        get {
            return self.homeScrollDelegate
        }
        set {
            self.homeScrollDelegate = homeDelegate
        }
     }

    func showButtons() {}
    func hideButtons() {}
}   

}

ParentViewController

// set childViewController.homeDelegate = self when creating children

extension ParentViewController: HomeScrollDelegate {
    weak var homeScrollDelegate: HomeScrollDelegate? {
        get {
            return self.homeScrollDelegate
        }
        set {
             if let homeController = UIViewController() as? HomeCollectionViewController {
                self.homeScrollDelegate = homeController.homeDelegate
            }

        }
    }

    func showButtons() {
         // show buttons
     }

    func hideButtons() {
        // hide Buttons
    } 
}

这些都不会被调用。我觉得我做的事情非常不正确。

下面是效果很好的代码,但我想要更通用的东西。我知道我可以很容易地设置一个协议,只需要任何需要的viewcontroller,就像这样:

protocol HomeScrollDelegate {
    func showButtons()
    func hideButtons()
}

class HomeCollectionViewController: UIViewController {
    weak var homeDelegate: HomeScrollDelegate?
    etc etc
}

extension HomeCollectionViewController: UICollectionViewDelegate {

    func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        if targetContentOffset.memory.y > scrollView.contentOffset.y {
             homeScrollDelegate?.hideButtons()
        } else {
            homeScrollDelegate?.showButtons()
        }
    }     
}

ParentViewController

extension ParentViewController: HomeScrollDelegate {
    func showButtons() {
         // show buttons
     }

    func hideButtons() {
        // hide Buttons
    } 
}

我这样做的目的是让我不必在每个UIScrollView委托中覆盖scrollViewWillEndDragging(_:_:_:),因为我将有其他不是UICollectionViews但会有scrollViews的childViewControllers。

0 个答案:

没有答案