【问题标题】:How to use UIScrollViewDelegate in Custom CollectionView?如何在自定义 CollectionView 中使用 UIScrollViewDelegate?
【发布时间】:2020-03-04 07:54:24
【问题描述】:

我正在为我的应用创建自定义集合视图。
我想在 ViewController 上滚动 CustomCollectionView 时调用 scrollViewWillEndDragging 方法。

当它在屏幕上绘制 CustomCollectionView 时,调用了 CommonInit,但是当我滚动它时没有调用 scrollViewWillEndDragging。

我怎么称呼它?

这是我的代码。

在自定义视图中

class CustomView: UICollectionView {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
    …
   }
}

extension CustomView: UIScrollViewDelegate {

// want to call this method
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
    {
}

在 AViewController 中

class AViewController: UIViewController {
    @IBOutlet weak var collectionView: CustomView!
    …
    override func viewDidLoad() {
    …
    collectionView.register(UINib(nibName: "Cell", bundle: nil), forCellWithReuseIdentifier: "Cell")
    …
    }
}

【问题讨论】:

    标签: ios swift uicollectionview uiscrollview


    【解决方案1】:

    您应该设置 collectionView 委托。您可以在 CustomView 中的 commonInit 中执行此操作,例如:

    delegate = self

    编辑

    你应该把UIScrollViewDelegate改成UICollectionViewDelegateUICollectionViewDelegate 继承自UIScrollViewDelegate

    【讨论】:

    • 我在 commonInit 中尝试了“delegate = self”。但是有一个编译错误并说“无法将'CustomView'类型的值分配给'UICollectionViewDelegate?”。所以我把它改成了“delegate = self as?UICollectionViewDelegate”。但是仍然没有调用scrollView方法..
    • @User17373928 我的错,我忘记了一些东西,你可以看到我的编辑:)
    • 你确定你的commonInit被调用了吗?
    • 所以问题出在你的初始化中,如果你从你的AViewController 调用commonInit 它工作正常吗?
    • 哦!!!我得到了它!!所以 AViewController 在 Storyboard 上也有 CustomView 的委托。我错过了.. 断开 AViewController 上的委托并完美工作!感谢你们对我的帮助! :-)
    猜你喜欢
    • 2023-03-30
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多