【问题标题】:Swift UICollectionView cellForItemAtIndexPath incorrect set cell contentSwift UICollectionView cellForItemAtIndexPath 设置单元格内容不正确
【发布时间】:2016-06-28 03:18:48
【问题描述】:

enter image description here

enter image description here

我想让按钮隐藏,只要它的标题等于'str'变量。

我无法添加更多照片,但它对“7:00”、“12:00”、“17:00”、“22:00”值的作用相同。 只想要“2:00”并为此进行比较。

这是 (collectionView)cellForItemAtIndexPath 错误还是其他问题?我很混乱。请帮忙。。

【问题讨论】:

  • 只显示您尝试过的内容
  • 有两张图片显示我的代码块和输出。我想让水平集合视图只有在里面有按钮来显示 24 小时,如“01:00”、“02:00”、“..”。但是想设置一些与其他按钮不同的按钮。它将是隐藏按钮或不同的标题颜色。这个例子,我尝试隐藏标题为“02:00”的按钮
  • .. 但其他一些按钮也发生了变化,其标题为“7:00”、“12:00”、“17:00”。当我将水平collectionview向左或向右移动时,每次设置不同的按钮。这很奇怪,不是吗?

标签: swift swift2 uicollectionview uicollectionviewcell


【解决方案1】:

当您滚动时,它将重新使用单元格,因此您可以根据条件设置 hidden true false。我认为这是你的问题。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let hour = array[indexPath.row]
let str ="2:00"
 if(cell.hourBtn.titleLabel?.text ==str {
   cell.hourBtn.hidden = true
 }
  else {
   cell.hourBtn.hidden = false
  }
}

【讨论】:

    【解决方案2】:

    cellForItemAtIndexPath 中没有错误,是你隐藏单元格的label。所以它只是隐藏标签而不是删除单元格。如果您只想显示不等于2:00 的值,则需要为此创建一个额外的数组并将其提供给CollectionViewDelegate 方法。像这样创建一个全局数组和函数。

    var array: [Int] = [Int]()
    fun populateData() {
        for i in oldArray {
            if i != 2 {
                self.array.append(i)
            }
        }
        collectionView.reloadData()
    }
    

    现在在 CollectionViewDelegate 这样的方法中使用这个 array 对象

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         return self.array.count
    } 
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let hour = array[indexPath.row]
        cell.hourBtn.setTitle("\(hour):00", forState: .Normal)
        //Now there is no need to write code for hiding button
    }
    

    希望这会对你有所帮助。

    【讨论】:

    • 它可以工作,但是如果我想显示该按钮但只想将其颜色设置为与其他按钮不同,我该怎么办?当我尝试将其颜色设置为不同并尝试将水平集合视图从右到左或从左到右移动时,不断更新按钮颜色并且每次移动不同的按钮而不是我想要的。
    • 不明白你想说什么。简要说明。您要更改哪种按钮颜色?
    • 根据您的解决方案,有一个包含几个小时的数组。但我想展示所有时间,其中一些具有不同的品质。当我移动collectionview时,每次它都会改变不同的按钮颜色。显然,这都是关于“其他”的:)。
    猜你喜欢
    • 2018-12-27
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多