ios - UICollectionView 不能在 ViewController.swift 中使用 IBOutlets
问题描述
例如,我按照随附的指南创建静态 UICollectionView,但现在我想为每个单元格添加按钮并更改按钮上的文本。我无法执行此操作并收到错误“UIButton 无效。插座无法连接到重复内容。” 如何解决此问题并在不离开 ViewController 的情况下将 IBOutlets 与单元格中的对象一起使用?
如果我需要离开 ViewController,请详细描述该过程,因为我是初学者,对不同的视图类不太了解。
谢谢!!
解决方案
而不是按钮和视图控制器之间的出口,您应该创建一个子类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
}
}
推荐阅读
- php - PHP文件上传和编辑
- php - Laravel 5.4:令牌不匹配异常
- javascript - 在加载可视化之前应用过滤器
- json - Ruby:如何将 json 解析为特定类型
- angular - 如何在C3.js中更改y轴标签的标签字体大小和颜色
- python - 尝试根据基于 django 的投票应用教程安装我自己的包
- solidity - 不允许从“literal_string”到“字符串存储指针”的显式类型转换
- php - 我想根据下拉选择列表显示数据
- r - R Shiny:如何在 DT::renderDataTable 中添加分页
- unicode - 有多少种 Unicode 编码,它们都还在使用吗?