ios - 使用 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直接设置它。
解决方案
推荐阅读
- javascript - 处理数组 Javascript 或 Jquery 问题的提示
- reactjs - 带有“npx create-react-app”的 IPFS-JS 导致 Webpack 错误
- reactjs - 使用 useContext 计算添加的次数 - React 和 Typescript
- c++ - 无法在 mingw64 上编译洞察调试器
- apostrophe-cms - 更改值的公共用户功能
- java - 可以重新安排被阻塞的线程来做其他工作吗?
- flutter - 没有用户身份验证的 Firestore 安全规则
- javascript - Angular Scroll-Into-View - 但仅适用于视图外的项目(需要滚动到)
- asp.net-web-api - 从控制器返回 ADO.Net 查询作为 JSON 数组
- php - 数字集合评分系统(序列号)