首页 > 解决方案 > 使用 IBInspectable 设置 UINavigationBar 的渐变颜色

问题描述

所以这是我的自定义类UINavigationBar

import UIKit

@IBDesignable
class GradientNavigationBar: UINavigationBar {

    @IBInspectable var firstColor: UIColor = UIColor.clear {
        didSet {
            updateView()
        }
    }

    @IBInspectable var secondColor: UIColor = UIColor.clear {
        didSet {
            updateView()
        }
    }

    @IBInspectable var isHorizontal: Bool = true {
        didSet {
            updateView()
        }
    }

    override class var layerClass: AnyClass {
        get {
            return CAGradientLayer.self
        }
    }

    func updateView() {
        let layer = self.layer as! CAGradientLayer
        layer.colors = [firstColor, secondColor].map {$0.cgColor}
        if (isHorizontal) {
            layer.startPoint = CGPoint(x: 0, y: 0.5)
            layer.endPoint = CGPoint (x: 1, y: 0.5)
        } else {
            layer.startPoint = CGPoint(x: 0.5, y: 0)
            layer.endPoint = CGPoint (x: 0.5, y: 1)
        }

        setBackgroundImage(layer.createGradientImage(), for: UIBarMetrics.default)
    }
}  

CAGradientLayer 扩展:

import Foundation
import UIKit

extension CAGradientLayer {

    convenience init(frame: CGRect, colors: [UIColor]) {
        self.init()
        self.frame = frame
        self.colors = []
        for color in colors {
            self.colors?.append(color.cgColor)
        }
        startPoint = CGPoint(x: 0, y: 0)
        endPoint = CGPoint(x: 0, y: 1)
    }

    func createGradientImage() -> UIImage? {

        var image: UIImage? = nil
        UIGraphicsBeginImageContext(bounds.size)
        if let context = UIGraphicsGetCurrentContext() {
            render(in: context)
            image = UIGraphicsGetImageFromCurrentImageContext()
        }
        UIGraphicsEndImageContext()
        return image
    }

}  

故事板属性:

在此处输入图像描述

故事板上的输出:

在此处输入图像描述

预期输出:

在此处输入图像描述

注意:我只需使用代码即可轻松完成此操作。我想要的是使用IBInspectable,以便我可以通过IB直接设置它。

标签: iosswiftstoryboarduinavigationbaribinspectable

解决方案


推荐阅读