【问题标题】:How can I change my custom cell background when pressing a button?按下按钮时如何更改自定义单元格背景?
【发布时间】:2021-03-23 06:55:23
【问题描述】:

我在 UIView 中有一个 CollectionView 和一个 Button。按钮的目的是改变应用程序的主题,我可以改变所有颜色,除了我的 TatodexCell(自定义单元格)上的 nameContainerView 的背景颜色。

我不知道如何访问该属性,然后更改我想要的颜色。

以下代码位于我的 TatodexController 文件中

我的按钮属性是:

    let buttonChangeTheme: UIButton? = {
    let button = UIButton()
    button.setTitle("Change to blue theme", for: .normal)
    button.addTarget(self, action: #selector(themeButtonClicked), for: .touchUpInside)
    button.titleLabel?.adjustsFontSizeToFitWidth = true
    button.layer.borderWidth = 3
    button.layer.borderColor = Colors.mainBlack?.cgColor
    button.backgroundColor = Colors.darkBlue
    button.tintColor = Colors.mainWhite
   return button
}()

我的按钮功能是这个:

    @objc func themeButtonClicked() {
    
    clickCheck = !clickCheck
    
    if clickCheck {
        navigationController?.navigationBar.barTintColor = Colors.lightBlue
        collectionViewPokemon?.backgroundColor           = Colors.darkBlue
        buttonChangeTheme?.backgroundColor               = Colors.darkRed
        buttonChangeTheme?.setTitle("Return to red theme", for: .normal)
        }
    else {
        navigationController?.navigationBar.barTintColor = Colors.lightRed
        collectionViewPokemon?.backgroundColor           = Colors.darkRed
        buttonChangeTheme?.backgroundColor               = Colors.darkBlue
        buttonChangeTheme?.setTitle("Change to blue theme", for: .normal)
    }
}

以下代码位于我的 TatodexCell 文件中

我要修改的nameContainerView的bg颜色是:

 lazy var nameContainerView: UIView = {
    
   let nameView              = UIView()
    nameView.backgroundColor = Colors.lightRed
    nameView.addSubview(nameLabel)
    nameLabel.center(inView: nameView)
    return nameView
}()

我的目标是将nameView.backgroundColor = Colors.lightRed 更改为nameView.backgroundColor = Colors.lightBlue,但我无法访问该属性。

我非常感谢任何帮助或建议。也许解决方案隐藏在显而易见的地方,但我尝试了很多方法,但都没有奏效。让我知道是否需要显示另一段代码。

【问题讨论】:

    标签: swift button uicollectionviewcell background-color


    【解决方案1】:

    如果您在自定义集合视图单元格中实现 tintColorDidChange() 方法,并在该方法中将单元格的背景颜色设置为色调颜色,那么当您更改拥有 UICollectionView 的色调颜色时,单元格的 tintColorDidChange() 方法会触发,你会看到变化。

    【讨论】:

    • 我在我的自定义collectionViewCell override func tintColorDidChange() { nameContainerView.backgroundColor = Colors.lightBlue } 上添加了这个方法,然后在我的themeButtonClicked 函数上调用它,但它不起作用
    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多