【问题标题】:How to set the title of a UIButton in a UICollectionViewCell with Swift如何使用 Swift 在 UICollectionViewCell 中设置 UIButton 的标题
【发布时间】:2016-02-03 18:09:41
【问题描述】:

我有一个带有 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 PlayerCell : UICollectionViewCell {

   @IBOutlet var button: UIButton?

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

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

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

我已在 Storyboard 中的单元格内添加了按钮,并将这些按钮与引用插座连接

我错过了什么吗?

在 Swift 2.0 中使用 xCode 7

【问题讨论】:

  • 现在发生了什么?
  • 我已经更新了我的问题,我添加了错误
  • 一个问题,你把按钮连接到文件所有者还是类?
  • Erm.. 我真的不明白你的意思,因为这是我用 iOS 制作的第一个应用程序。我所做的是将按钮 ctrl 拖动到单元格并单击“按钮”,因为这是列表中显示的 IBOutlet 的名称

标签: ios swift uibutton uicollectionview uicollectionviewcell


【解决方案1】:

尝试: 1. 我会检查按钮上没有连接旧的参考插座。右键单击界面生成器中的按钮并确保仅连接了适当的插座。

  1. 确保在情节提要中已将可重用单元格的类设置为 PlayerCell

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

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

【讨论】:

    【解决方案2】:

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

    当您的应用加载您在情节提要中设计的集合视图控制器时,控制器会负责为单元格注册单元格的 XIB 文件。

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

    去掉这一行:

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

    另外,请确保在情节提要中将单元格的重用标识符设置为“PlayerCell”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多