Swift 3泛型:在UITableViewCell中设置UICollectionView的UICollectionView的UICollectionViewDatasource&Delegate问题
问题描述:
我正在将我的应用程序翻译成Swift 3.我偶然发现了一个使用干净的方式为UICollectionView设置数据源和委托的问题在一个UITableViewCell里面,描述为here。Swift 3泛型:在UITableViewCell中设置UICollectionView的UICollectionView的UICollectionViewDatasource&Delegate问题
的代码如下:
func setCollectionViewDataSourceDelegate<D: protocol<UICollectionViewDataSource, UICollectionViewDelegate>>
(_ dataSourceDelegate: D, forRow row: Int) {
collectionView.delegate = dataSourceDelegate
collectionView.dataSource = dataSourceDelegate
collectionView.tag = row
collectionView.reloadData()}
它抛出一个警告,指出:
'protocol<...>' composition syntax is deprecated; join the protocols using '&'
当我接受建议的解决方案,它改变了D: protocol<UICollectionViewDataSource, UICollectionViewDelegate>
成D: (UICollectionViewDatasource & UICollectionViewDelegate)
通话,而是抛出一个错误:
Expected a type name or protocol composition restricting 'D'
我会很ob如果有人比我更了解Swift 3泛型可以提出解决方案。
答
不需要使用protocol<>
,因为编译器已经知道了。刚刚加入该协议是这样的:D: UITableViewDelegate & UITableViewDataSource
答
setCollectionViewDataSourceDelegate为swift3
extension PollTableViewCell {
func setCollectionViewDataSourceDelegate<D: UICollectionViewDataSource & UICollectionViewDelegate>(_ dataSourceDelegate: D, forRow row: Int) {
theCollectionView.delegate = dataSourceDelegate
theCollectionView.dataSource = dataSourceDelegate
theCollectionView.tag = row
theCollectionView.setContentOffset(theCollectionView.contentOffset, animated:false) // Stops collection view if it was scrolling.
theCollectionView.reloadData()
}
var collectionViewOffset: CGFloat {
set {
theCollectionView.contentOffset.x = newValue
}
get {
return theCollectionView.contentOffset.x
}
}
}
不知道为什么Xcode的修复建议抛出括号,只需删除它们固定的问题。非常感谢! – michalronin