【问题标题】:Change navigationBar bottom border to a dashed line in swift在swift中将navigationBar底部边框更改为虚线
【发布时间】:2019-02-22 00:43:38
【问题描述】:

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

我在这个帖子中找到了一个关于如何更改导航栏边框颜色的精彩答案:Change navigation bar bottom border color 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))

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

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

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

    还有这个关于将 CALayer 转换为 UIImage 的 SO 线程:UIImage from CALayer in iOS

    整体流程是:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      相关资源
      最近更新 更多