使用IBInspectable设置UINavigationBar的渐变颜色

时间:2018-06-06 06:22:16

标签: ios swift storyboard uinavigationbar ibinspectable

这是我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
    }

}  

故事板属性:

enter image description here

故事板上的输出:

enter image description here

预期输出:

enter image description here

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

0 个答案:

没有答案