在iOS 10中,我可以这样做来制作背景渐变:
let gradientColor = UIColor.gradientWithFrame(frame: navigationBar.bounds, colors: [.red, .blue])
navigationBar.barTintColor = gradientColor
现在,navigationBar.bounds
在没有大标题的情况下返回UINavigationBar
的大小。在此屏幕截图中显示渐变重复:
您可以看到渐变开始重复,因为navigationBar.size
返回的大小返回不正确的大小。
还有另一种方法在UINavigationBar
上设置渐变吗?
我将导航栏色调设置为“清除颜色”,并将渐变添加到背景视图。
您需要考虑我的6s设备上的状态栏高度20,您可以使用UIApplication.shared.statusBarFrame.height
并简单地将此高度添加到框架。
另外,我通过从CAGradientLayer创建UIImage来设置渐变,所以我可以使用UIColor(patternImage:)
方法。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.prefersLargeTitles = true
self.title = "Feed me Seymour"
if let navFrame = self.navigationController?.navigationBar.frame {
//HERE
//Create a new frame with the default offset of the status bar
let newframe = CGRect(origin: .zero, size: CGSize(width: navFrame.width, height: (navFrame.height + UIApplication.shared.statusBarFrame.height) ))
let image = gradientWithFrametoImage(frame: newframe, colors: [UIColor.red.cgColor, UIColor.blue.cgColor])!
self.navigationController?.navigationBar.barTintColor = UIColor(patternImage: image)
}
}
func gradientWithFrametoImage(frame: CGRect, colors: [CGColor]) -> UIImage? {
let gradient: CAGradientLayer = CAGradientLayer(layer: self.view.layer)
gradient.frame = frame
gradient.colors = colors
UIGraphicsBeginImageContext(frame.size)
gradient.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}