ios - 为什么 UICollectionView 的委托方法不起作用?
问题描述
我创建了一个collectionView
,并使它的委托符合UICollectionViewDelegateFlowLayout
附加到主ViewController的协议,以便修改UICollectionView's
单元格的某些方面。最初我是这样做的:
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.delegate = self
}
然后我意识到这不起作用,因为有一个错误,所以我修复了它:
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.delegate = self as? UICollectionViewDelegateFlowLayout
}
问题是我尝试在ViewController中实现的每个方法在运行时似乎都不起作用。
我在这里实现了这个方法:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width/3, height: collectionView.frame.width/3)
}
但它在应用程序运行期间不起作用。
解决方案
“所以我把它修好了”
你让错误消失了,但你没有修复它。您需要通过将视图控制器类UICollectionViewDelegateFlowLayout
添加到其类声明中来使视图控制器类实际采用,如下所示:
class ProfileViewController: UIViewController, UICollectionViewDelegateFlowLayout {
或将其添加到视图控制器的扩展中,如下所示:
extension ProfileViewController: UICollectionViewDelegateFlowLayout {
推荐阅读
- sql - 没有明确列出列名的 SQL 联合 NULL 列
- go - 除了结构字段标签之外的其他元数据
- amazon-web-services - 如何从生产者 lambda 到消费者 lambda 获取 SQS 批次?
- java - 在 return 中编写 if 语句
- javascript - NodeJS - 使用“--trace-sync-io”得到“警告:检测到使用同步 API”
- python - 获取 ServerDisconnectedError 异常,Connection.release() 会帮助解决这个问题吗?
- python - 如何使用 operator.itemgetter 来检查过滤器函数而不是 lambda 中的条件?
- excel - Graph Excel API:如何设置计算模式(以提高性能)
- c# - 使用 OAuth2 客户端凭据流保护 Azure API 管理中的后端服务
- angular - 用柏树拖放角树组件