【问题标题】:How to create and use UIcollectionView programmatically?如何以编程方式创建和使用 UIcollectionView?
【发布时间】:2014-11-26 11:20:35
【问题描述】:

我已经搜索了很多以编程方式创建UICollectionView,但没有一个建议使用它的最简单方法,即如何将标签或图像添加到UICollectionViewCell。大多数网站建议UICollectionView 的实现与UITableView 相同,但主要区别在于我们尝试添加任何图像时。在UITableView 中,我们可以在cellForRow 方法cell == nil 中分配图像视图,并在其中分配图像(cell != nil)。但这里在UICollectionView ItemAtIndexPath 方法的情况下,没有条件(cell == nil),如UITableViewCellForRow。结果,我们无法在itemAtIndexPath 方法中有效地分配UImageViews 或标签等变量。我想知道除了子类化UICollectionViewCell 并在该自定义类中分配变量之外是否还有其他选择?任何人都可以帮助,任何帮助表示赞赏。

【问题讨论】:

  • 也许这篇博文和我做的相应 github 仓库对你有帮助:dasdev.de/2013/12/27/…
  • 在某种程度上是的,但我们必须在你建议的链接中对 NSObject 进行子类化。因此,要添加标签,除了 uitableview 类中不需要的子类之外别无他法。还是谢谢。

标签: ios iphone uicollectionview


【解决方案1】:

在 itemAtIndex 方法中没有创建或分配单元格的替代方法。我们需要注册自定义类以在自定义类中创建任何视图。像这样:

[UICollectionView registerClass:[CustomCollectionViewClass class] forCellWithReuseIdentifier:@"cellIdentifier"];

here 是我发现有用的最佳链接。希望对其他人有所帮助

【讨论】:

    【解决方案2】:

    迅速:

       override func viewDidLoad() {
           super.viewDidLoad()
    
           let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
           layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
           layout.itemSize = CGSize(width: 70, height: 70)
    
           let demoCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
           demoCollectionView.dataSource = self
           demoCollectionView.delegate = self
           demoCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
           demoCollectionView.backgroundColor = UIColor.whiteColor()
           self.view.addSubview(demoCollectionView)
       }
    
       func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
           return 27
       }
    
       func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
           let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
           cell.backgroundColor = UIColor.lightGrayColor()
           return cell
       }
    
       func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
      {
           print("User tapped on item \(indexPath.row)")
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-25
      • 2016-02-19
      • 2022-10-31
      • 2023-04-01
      • 2017-08-22
      • 2018-01-22
      • 1970-01-01
      相关资源
      最近更新 更多