【问题标题】:Outlets cannot be connected to repeating content插座无法连接到重复内容
【发布时间】:2018-06-24 21:45:12
【问题描述】:

我用Collection View Cell 创建了Collection View。在Collection View Cell 里面我插入了UIButton。现在因为错误无法连接插座:

从 ViewController 到 UIButton 的 firstPercent 出口是 无效的。插座不能连接到重复的内容。

我该如何解决?

【问题讨论】:

  • 您不能将原型单元格中的按钮连接到 UIViewController 子类中的 IBOutlet - 您必须将其连接到 UICollectionviewCell 子类中的 IBOutlet。

标签: swift


【解决方案1】:

听起来您正在尝试将按钮连接到您的 ViewController,您不能这样做,因为按钮所在的单元格重复。要连接按钮,您需要将按钮连接到 UICollectionViewCell 类。我将在下面给你一个关于如何设置你的单元的例子。

class Cell: UICollectionViewCell {

     @IBOutlet var button: UIButton!

     override init(frame: CGRect) {
          super.init(frame: frame)
     }
     required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
     }
}

根据评论更新:

class ViewController: UIViewController {
    //other code
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! Cell
        cell.button.addTarget(target: self, action: #selector(buttonTapped), for: .touchUpInside)

        return cell
    }

    @objc func buttonTapped() {
        print("do stuff here")
    }
}

【讨论】:

  • 感谢您的帮助。我也有一个问题。如何在另一个类中使用此按钮的 var?我需要在点击等时更改按钮颜色。
  • 我建议将该按钮链接到使用 cellForItemAt 的函数,我将更新我的答案以向您展示。
猜你喜欢
  • 2014-12-21
  • 2015-10-11
  • 2015-01-24
  • 2015-07-12
  • 2018-08-12
  • 2017-06-08
  • 2018-02-04
  • 2021-04-08
相关资源
最近更新 更多