如何使用 Swift 在 UICollectionViewCell 中设置 UIButton 的标题

How to set the title of a UIButton in a UICollectionViewCell with Swift

我有一个带有 UICollectionView 的 ViewController,我想在其中显示用户好友列表中玩家的前两个字母,如下所示:

func collectionView(collectionView: UICollectionView,
    cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        contactListCollection.registerClass(PlayerCell.self, forCellWithReuseIdentifier: "PlayerCell")

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PlayerCell", forIndexPath: indexPath) as! PlayerCell

        let contacts = contactList.getContactList() //Array of strings

        for(var i = 0; i < contacts.count; i++){

            var str = contacts[i]
            // First two letters
            let firstTwo = Range(start: str.startIndex,
                end: str.startIndex.advancedBy(2))

            str = str.substringWithRange(firstTwo)

            cell.setButtonTitle(str);
        }


        return cell;
}

func collectionView(collectionView: UICollectionView,
  numberOfItemsInSection section: Int) -> Int {

    return contactList.getContactList().count;
}

我的PlayerCell Class如下:

   class PlayerCell : UICollectionViewCell {

   @IBOutlet var button: UIButton?

   func setButtonTitle(text: String){
     button!.setTitle(text, forState: .Normal)
   }
}

当运行它给出的代码: 致命错误:在展开可选值时意外发现 nil

我发现我的 PlayerCell 中的按钮是 nil

我已经在 Storyboard 中的单元格内添加了按钮,并将它们与引用插座连接起来

我是不是漏掉了什么?

使用 xCode 7 和 Swift 2.0

作为编译过程的一部分,Xcode 将故事板转换为 XIB 文件的集合。这些 XIB 文件之一包含您的单元格设计。

当您的应用程序加载您在故事板中设计的集合视图控制器时,该控制器负责为单元格注册单元格的 XIB 文件。

您正在通过调用 registerClass(_:forCellWithReuseIdentifier:) 覆盖该注册,切断“PlayerCell”重用标识符与包含 PlayerCell 设计的 XIB 之间的连接。

去掉这一行:

contactListCollection.registerClass(PlayerCell.self, forCellWithReuseIdentifier: "PlayerCell")

此外,请确保您已在故事板中将单元格的重用标识符设置为 "PlayerCell"。

尝试: 1. 我会检查按钮上没有连接旧的参考插座。右键单击界面构建器中的按钮,确保只有适当的插座仍然连接。

  1. 确保在故事板中您已将可重用单元格的 class 设置为 PlayerCell

  2. 确保您已按 Ctrl + 从集合视图拖动到它所在的视图控制器,并将委托和数据源设置为其自身。

希望其中之一对您有所帮助。