当在 UICollectionView.visibleCells() 中循环遍历 UICollectionViewCells 数组然后检查单元格是否符合协议(protocol)时,它会忘记该单元格是 UIView 并且具有框架属性。
for cell in collectionView.visibleCells() {
let cellPosition1 = cell.frame.origin
if let cell = cell as? AwesomeCellProtocol {
let cellPosition2 = cell.frame.origin
cell.doAwesome(cellPosition)
}
}
Swift 在设置 cellPosition2 时给出编译错误:
Value of type 'AwesomeCellProtocol' has no member 'frame'
设置 cellPosition1 效果很好。
我可以检查 UIView 和 AwesomeCellProtocol 吗?
最佳答案
与
if let cell = cell as? AwesomeCellProtocol { ... }
您为 if block 的范围引入了一个新变量 cell
,
它从 for 循环的外部范围“隐藏”cell
变量。
该局部变量的类型为 AwesomeCellProtocol
而不是
UICollectionViewCell
。
您可以通过绑定(bind)到不同的名称来避免该问题:
if let awesomeCell = cell as? AwesomeCellProtocol {
let cellPosition2 = cell.frame.origin
awesomeCell.doAwesome(cellPosition)
}
关于Swift 忘记对象是一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309253/