首页 > 解决方案 > 在swift中将navigationBar底部边框更改为虚线

问题描述

我想将我的导航栏更改为以虚线作为边框,如下所示:

截屏

我在这个线程中找到了一个关于如何更改导航栏边框颜色的精彩答案:更改导航栏底部边框颜色 Swift特别是:https ://stackoverflow.com/a/46224261/436014

通过 UIColor 扩展:

extension UIColor {

    /// Converts this `UIColor` instance to a 1x1 `UIImage` instance and returns it.
    ///
    /// - Returns: `self` as a 1x1 `UIImage`.
    func as1ptImage() -> UIImage {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        setFill()
        UIGraphicsGetCurrentContext()?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
        let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
        UIGraphicsEndImageContext()
        return image
    }
}

我想知道是否有任何方法可以调整它来构建一条虚线。我在想它可以通过绘制交替颜色的填充来完成,但我很困惑,因为这都是单个 UIcolor 的扩展

navigationController.navigationBar.shadowImage = UIColor.black.as1ptImage()

因此,类似以下的内容显然不起作用:

UIGraphicsBeginImageContext(CGSize(width: 1, height: 4))
UIGraphicsGetCurrentContext()?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
UIGraphicsGetCurrentContext()?.fill(CGRect(x: 1, y: 0, width: 3, height: 1))

我想知道是否有人知道如何解决这个问题

标签: iosswiftxcode

解决方案


好的,我设法通过 CALayer 的 API 文档找到了解决方案:https ://developer.apple.com/documentation/quartzcore/cashapelayer/1521921-linedashpattern

还有这个关于将 CALayer 转换为 UIImage 的 SO 线程:iOS 中来自 CALayer 的 UIImage

总体流程是:

  1. 创建一个CALayer
  2. 给这个CALayer框架
  3. 画一条虚线
  4. 转换成UIImage
  5. 使用这个 UIImage 作为navigationBar.shadowImage

好处是它可以适当地平铺,因此 CALayer/UIImage 只需要与您生成的虚线一样宽。

    extension UIImage {
        class func imageWithLayer(layer: CALayer) -> UIImage {
            UIGraphicsBeginImageContextWithOptions(layer.bounds.size, layer.isOpaque, 0.0)
            layer.render(in: UIGraphicsGetCurrentContext()!)
            guard let img = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage() }
            UIGraphicsEndImageContext()
            return img
        }
    }


    let layer = CALayer()
    layer.frame = CGRect(x: 0, y: 0, width: 6, height: 1)
    let shapeLayer = CAShapeLayer()
    shapeLayer.strokeColor = UIColor.black.cgColor
    shapeLayer.lineWidth = 1
    shapeLayer.lineDashPattern = [4,2]
    let path = CGMutablePath()
    path.addLines(between: [CGPoint(x:1, y: 0), CGPoint(x: 6, y:0)])
    shapeLayer.path = path
    layer.addSublayer(shapeLayer)
    navigationController.navigationBar.shadowImage = UIImage.imageWithLayer(layer: layer)

推荐阅读