Установите цвет градиента UINavigationBar, используя IBInspectable - PullRequest
0 голосов
/ 06 июня 2018

Так что это мой пользовательский класс для 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 .

...