为什么 UICollectionView 的委托方法不起作用?

Why does the UICollectionView's delegate methods don't work?

我创建了一个 collectionView 并使它的委托符合附加到主 ViewControllerUICollectionViewDelegateFlowLayout 协议,以便修改一些UICollectionView's 个单元格的各个方面。 最初我是这样做的:

override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView.delegate = self 

}

然后我意识到这是行不通的,因为有一个错误,所以我修复了它:

 override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView.delegate = self as? UICollectionViewDelegateFlowLayout

}

问题是我在 ViewController 中尝试实施的每个方法在 运行 时间似乎都不起作用。

f.e。我在这里实现了这个方法:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: collectionView.frame.width/3, height: collectionView.frame.width/3)

}

但在申请运行期间不起作用。

"so I fixed it doing this"

你让错误消失了,但你没有修复它。您需要通过将视图控制器 class 添加到它的 class 声明中来真正采用 UICollectionViewDelegateFlowLayout ,如下所示:

class ProfileViewController: UIViewController, UICollectionViewDelegateFlowLayout {

或者将其添加到视图控制器的扩展中,如下所示:

extension ProfileViewController: UICollectionViewDelegateFlowLayout {