【问题标题】:Change text color of UILabel inside Custom UICollectionViewCell在自定义 UICollectionViewCell 中更改 UILabel 的文本颜色
【发布时间】:2016-08-24 03:45:31
【问题描述】:

我一直在尝试更改UICollectionView 中自定义单元格内UILabel 的文本颜色。目前我正在使用以下代码,它允许我更改 Cell 的背景颜色,但我只需要更改文本颜色:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {

    //Change background color of selected Cell

    let selectedCell:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!

    selectedCell.contentView.backgroundColor = UIColor(red: 102/256, green: 255/256, blue: 255/256, alpha: 0.66)

    }


func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath)
    {

    //Set background color of selected Cell to Clear Color 

    let cellToDeselect:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!

    cellToDeselect.contentView.backgroundColor = UIColor.clearColor()

    }

我见过很少的应用程序在选定的单元格下不断移动细线之类的东西。任何人都知道如何实现它?

TIA

【问题讨论】:

    标签: ios swift uicollectionview uilabel uicollectionviewcell


    【解决方案1】:

    如果它是自定义单元格,则需要向自定义 UICollectionViewCell 添加标签

    import UIKit
    
    class CustomCell: UICollectionViewCell {
    
        let label: UILabel! = nil
    
    }
    

    然后,在 selectItemAtIndexPath:

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    
        let selectedCell: CustomCell = collectionView.cellForItemAtIndexPath(indexPath) as! CustomCell
        selectedCell.label.textColor = UIColor(red: 102/256, green: 255/256, blue: 255/256, alpha: 0.66)
    
    }
    

    【讨论】:

    • 非常感谢。这正是我需要的:)
    • 不客气。如果这有帮助,请选择它作为答案并点赞。
    【解决方案2】:
    theLableYouWantToChangeColor.textColor = UIColor.redColor()
    

    正如你所说的自定义UICollectionViewCell,你必须创建一个自定义UICollectionViewCell并在里面添加一个UILabel

    【讨论】:

    • 这正是我所做的: class SliderCustomCollectionViewCell: UICollectionViewCell { @IBOutlet var sliderCellLabel: UILabel! }
    • 现在如何让它在另一个类函数中可见。要具体说明 didSelect 和 deSelect 方法吗?最后改变文字的颜色...?
    • 在 cellforItems.... 创建单元格时使用它。我不明白你的意思是“现在我如何让它在另一个类函数中可见”
    • 我的意思是我可以在 cellForItemAtIndexPath() 中使用这个标签,但如果我想在其他方法中使用它,比如 didSelectItemAtIndexPath() 和 didDeselectItemAtIndexPath()。我该怎么做?因为更改所选单元格标签的文本颜色的代码必须进入这些方法。我希望它现在清楚了。否则,请随时再次 ping。
    • 简而言之,请告诉我在自定义 UICollectionViewCell 类中更改标签文本颜色的 didSelectItemAtIndexPath() 和 didDeselectItemAtIndexPath() 代码。
    【解决方案3】:

    您应该具有单元格引用,并使该标签属性可从其他类访问并访问和更改它或将颜色对象传递给单元格并仅在此处更改它。 其他检查:Reference 不应为 nil,如果 IBOutlet 则应连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 2011-02-01
      • 1970-01-01
      相关资源
      最近更新 更多