如何使用iOS 11和prefersLargeTitles为UINavigationBar设置背景渐变?

问题描述 投票:0回答:2

在iOS 10中,我可以这样做来制作背景渐变:

let gradientColor = UIColor.gradientWithFrame(frame: navigationBar.bounds, colors: [.red, .blue])
navigationBar.barTintColor = gradientColor

现在,navigationBar.bounds在没有大标题的情况下返回UINavigationBar的大小。在此屏幕截图中显示渐变重复:

enter image description here

您可以看到渐变开始重复,因为navigationBar.size返回的大小返回不正确的大小。

还有另一种方法在UINavigationBar上设置渐变吗?

ios swift
2个回答
0
投票

我将导航栏色调设置为“清除颜色”,并将渐变添加到背景视图。


0
投票

您需要考虑我的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
}

View of Navigation Bar View Hierarchy showing +20 to y offset

© www.soinside.com 2019 - 2024. All rights reserved.