【问题标题】:Why are UIViews background color is not updating?为什么 UIViews 背景颜色没有更新?
【发布时间】:2018-05-17 12:04:13
【问题描述】:

Switch 语句有效,但不会重置视图背景颜色等。

如下图所示,我有一个UIImage(图标)和一个嵌入在UIView(自定义类型DropShadowCircleView)中的UIButton

当点击步行按钮时,var navigationOption 被设置为walkingdriving 并执行setupNavigationSelectionView()

问题是:开关的“walking”案例完美运行,但“driving”案例没有重置UIView并将图标色调颜色恢复为原始设置,例如;背景颜色等。任何想法为什么?

func setupNavigationSelectionView(){

        switch navigationOption {

        case "walking":
            walkingBg.setGradientBackground(colourOne: softGreen, ColourTwo: softBlue)
            walkingBg.layer.cornerRadius = walkingBg.frame.width / 2
            walkingBg.clipsToBounds = true
            walkingIcon.tintColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)

        case "driving":
            walkingBg.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
            walkingBg.layer.cornerRadius = walkingBg.frame.width / 2
            walkingBg.clipsToBounds = true
            walkingIcon.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)

        default:
            break

        }
}

编辑:这是我的DropShadowCircleView 课程

class DropShadowCircleView: UIView {

    override func awakeFromNib() {

        setupView()
        super.awakeFromNib()

    }

    func setupView(){
        self.layer.shadowOpacity = 0.50
        self.layer.shadowRadius = 20
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.cornerRadius = self.frame.width / 2


    }

}

编辑:这是我的 setGradientBackground 函数,它位于 UIView 的扩展文件中

func setGradientBackground(colourOne: UIColor, ColourTwo: UIColor) {

        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        gradientLayer.colors = [colourOne.cgColor, ColourTwo.cgColor]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
        gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)

        layer.insertSublayer(gradientLayer, at: 0)
    }

【问题讨论】:

  • 请将DropShadowCircleView的代码添加到您的问题中。
  • @vacawama 我已经用 DropShadowCircleView 类更新了我的问题。
  • setGradientBackground 在哪里实现?它有什么作用?
  • @vacawama 我再次编辑了我的问题以包含 setGradientBackground 函数

标签: swift uiview


【解决方案1】:

重置图标时需要移除渐变层。

将此添加到您的extension UIView

func removeGradientBackground() {
    guard
        let idx = layer.sublayers?.index(where: { $0 is CAGradientLayer })
        else { return }

    layer.sublayers?.remove(at: idx)
}

并在您重置图标时调用它。

【讨论】:

  • 这非常有效,感谢@vacawama 感谢您的帮助。一个小问题是walkingIcon.tintColor to black 不起作用。
  • 定义“不工作”。它有什么作用?你期望它做什么?
  • 我现在可以使用它了,我必须先将 UIImage 视图的渲染模式设置为 .alwaysTemplate,然后才能在其上使用 tintColor。
猜你喜欢
  • 2023-04-05
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 2020-05-18
  • 2011-08-18
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
相关资源
最近更新 更多