部分更改UIView的背景颜色

时间:2018-10-24 09:33:07

标签: ios swift

我有一个带有一些标签的UIView和一个UITableViewCell的背景色。当它显示时,我希望将背景颜色分为两种(红色为30%,灰色为70%)。我试图隐藏使用子层,但是,这很棘手,因为在点击时我的单元格会随机调整大小,因此我必须手动更新子层的CGRect。关于如何以其他方式执行操作的任何想法?

这就是我尝试过的。它可以完成任务,但是很难管理resize事件。 (渐变只是为了使其丰富多彩)

extension UIView{
    func addGradientLayer(points: Float){

        let gradientLayer: CAGradientLayer! = CAGradientLayer()
        gradientLayer.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor, UIColor.green.cgColor]
        gradientLayer.locations = [0.0, 0.6, 1.0]
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        gradientLayer.frame = bounds
        let layer1 = CALayer()
        let x = CGFloat(points/100) * layer.bounds.width
        let frameOn = CGRect(x: x, y: 0.0, width: bounds.width - x, height: bounds.height)
        layer1.cornerRadius = 20
        gradientLayer.cornerRadius = 20
        layer1.frame = frameOn
        layer1.backgroundColor = UIColor.lightGray.cgColor
        layer.insertSublayer(layer1, at: 0)
        layer.insertSublayer(gradientLayer, at: 0)
    }
}

1 个答案:

答案 0 :(得分:0)

您好,希望对您有帮助

//Top to Bottom Gradient
extension UIView {
    func setGradientBackground() {
        let colorTop =  UIColor.red.cgColor
        let colorBottom = UIColor.blue.cgColor

        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.startPoint =  CGPoint(x: 1.0, y: 0.0)
        gradientLayer.endPoint =  CGPoint(x: 1.0, y: 0.7)
        gradientLayer.frame = self.bounds

        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}

//Left to Right Gradient
extension UIView {
    func setGradientBackground() {
        let colorLeft =  UIColor.red.cgColor
        let colorRight = UIColor.blue.cgColor

        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorLeft, colorRight]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.startPoint =  CGPoint(x: 0.0, y: 1.0)
        gradientLayer.endPoint =  CGPoint(x: 0.3, y: 1.0)
        gradientLayer.frame = self.bounds

        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}

enter image description here