swift - 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
}
}
我究竟做错了什么?
解决方案
我想你正在寻找这样的东西
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
推荐阅读
- html - 由于 ngModel,角度检查功能被忽略
- vim - Vim - 选择当前单词的多个实例并同时更改 - 对所有搜索结果执行操作而不使用替换?
- c - Eclipse (mingw-w64) 编译但仍包含阻止调试会话的错误
- qt - 弹出窗口,周围有模糊
- wordpress - ACF 中继器手风琴循环问题
- python - Python:引发异常类(消息,屏幕,堆栈跟踪)selenium.common.exceptions.UnexpectedAlertPresentException:警报文本:无消息:
- c - 拆分单个输入并存储在单个变量中
- azure-service-fabric - 运行具有可靠集合的 Service Fabric 群集的 Azure VM 的存储
- javascript - 如何在 Typescript 中声明模块的全局变量?
- magento2 - 您如何将 Google 再营销与 Magento 2 联系起来?