首页 > 解决方案 > UIScrollView Delegate 作为协议默认实现

问题描述

我正在尝试为UIScrollViewDelegate方法实现默认实现:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)

使用protocol.

如果我把这个方法放在类中,它就会被调用;但是,如果我尝试通过 用作默认实现protocol,则永远不会调用它。

代码:

protocol DefaultScrollViewEndDragging {
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
}

extension DefaultScrollViewEndDragging {
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        print("scrollViewWillEndDragging is called")
        // THIS IS NEVER CALLED
    }
}

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, DefaultScrollViewEndDragging {

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
        print("Cell \(indexPath.row)")
        cell.contentView.backgroundColor = .orange
        return cell
    }
}

我究竟做错了什么?

标签: swiftuiscrollviewuicollectionviewswift-protocols

解决方案


我想你正在寻找这样的东西

protocol DefaultScrollViewEndDragging : UIScrollViewDelegate {
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
}

extension DefaultScrollViewEndDragging {
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        print("scrollViewWillEndDragging is called")
        // THIS IS NEVER CALLED
    }
}

不幸的是,Obj-C 无法访问协议扩展。所以它没有被调用 scrollViewWillEndDragging

来自注释

同样,唯一的例外是协议扩展。与该语言中的任何其他构造不同,协议扩展方法是在虚拟分派会导致不同结果的情况下静态分派的。没有编译器错误可以防止这种不匹配。 https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001707.html


推荐阅读