首页 > 解决方案 > UICollectionView 不能在 ViewController.swift 中使用 IBOutlets

问题描述

例如,我按照随附的指南创建静态 UICollectionView,但现在我想为每个单元格添加按钮并更改按钮上的文本。我无法执行此操作并收到错误“UIButton 无效。插座无法连接到重复内容。” 如何解决此问题并在不离开 ViewController 的情况下将 IBOutlets 与单元格中的对象一起使用?

如果我需要离开 ViewController,请详细描述该过程,因为我是初学者,对不同的视图类不太了解。

谢谢!!

标签: iosswiftuicollectionviewiboutlet

解决方案


而不是按钮和视图控制器之间的出口,您应该创建一个子类UICollectionViewCell,并在该类上添加您的 IBOutlets。

class MyCollectionViewCell: UICollectionViewCell {
    @IBOutlet var myButton: UIButton!
}

然后,在 Interface Builder 中,将此子类设置为您的单元格的类(在身份检查器窗格中)。

身份检查员

然后,您应该能够创建从按钮到单元的插座连接。

添加插座连接

我希望这足够清楚。如果没有,请告诉我!

示例代码

class MyCollectionViewCell: UICollectionViewCell {
    @IBOutlet var myButton: UIButton!
}

class MyViewController: UIViewController, UICollectionViewDataSource {
    @IBOutlet var myCollectionView: UICollectionView!

    private var isMyButtonEnabled = true

    // Other view controller code

    func disableMyButton() {
        self.isMyButtonEnabled = false
        self.myCollectionView.reloadData()
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = ... as! MyCollectionViewCell // Get cell
        // Other cell setup

        cell.myButton.isEnabled = self.isMyButtonEnabled

        return cell
    }
}

推荐阅读