Swift 协议语法,其中 Self: 既是 UICollectionViewDataSource 又是 UICollectionViewDelegate
Swift protocol syntax where Self: is both UICollectionViewDataSource and UICollectionViewDelegate
我正在尝试创建一个协议,该协议会自动将 UICollectionView 添加到符合要求的任何 UIViewController。
这是我当前的代码:
protocol ReusableNavigation {
var actionContainer: UIView! { get }
func addActionMenuCollection()
}
extension ReusableNavigation where Self: UICollectionViewDataSource {
func addActionMenuCollection() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 60, height: 60)
let actionMenu:UICollectionView = UICollectionView(frame: self.actionContainer.frame, collectionViewLayout: layout)
actionMenu.dataSource = self
actionMenu.delegate = self
actionMenu.register(UINib(nibName: "ActionCell", bundle: nil), forCellWithReuseIdentifier: "actionCell")
actionMenu.semanticContentAttribute = UISemanticContentAttribute.forceRightToLeft
self.actionContainer.addSubview(actionMenu)
}
}
显然,上面的代码在我尝试设置 actionMenu 委托时出错,因为 self 只是一个 UICollectionViewDataSource
我这辈子都想不出协议扩展的语法,其中 self 等于 UICollectionViewDataSource 和 UICollectionViewDelegate。
可能吗?想法?
添加约束以逗号分隔
extension ReusableNavigation where Self: UICollectionViewDataSource, Self: UICollectionViewDelegate { ...
或与号连接
extension ReusableNavigation where Self: UICollectionViewDataSource & UICollectionViewDelegate
我正在尝试创建一个协议,该协议会自动将 UICollectionView 添加到符合要求的任何 UIViewController。
这是我当前的代码:
protocol ReusableNavigation {
var actionContainer: UIView! { get }
func addActionMenuCollection()
}
extension ReusableNavigation where Self: UICollectionViewDataSource {
func addActionMenuCollection() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 60, height: 60)
let actionMenu:UICollectionView = UICollectionView(frame: self.actionContainer.frame, collectionViewLayout: layout)
actionMenu.dataSource = self
actionMenu.delegate = self
actionMenu.register(UINib(nibName: "ActionCell", bundle: nil), forCellWithReuseIdentifier: "actionCell")
actionMenu.semanticContentAttribute = UISemanticContentAttribute.forceRightToLeft
self.actionContainer.addSubview(actionMenu)
}
}
显然,上面的代码在我尝试设置 actionMenu 委托时出错,因为 self 只是一个 UICollectionViewDataSource
我这辈子都想不出协议扩展的语法,其中 self 等于 UICollectionViewDataSource 和 UICollectionViewDelegate。
可能吗?想法?
添加约束以逗号分隔
extension ReusableNavigation where Self: UICollectionViewDataSource, Self: UICollectionViewDelegate { ...
或与号连接
extension ReusableNavigation where Self: UICollectionViewDataSource & UICollectionViewDelegate