ios - 如何为 UIView 的任何特定边缘添加虚线边框?

标签 ios swift view border

如何只在 UIView 的某边添加虚线边框?引用Dashed line border around UIView链接,但在给出 View 所有边缘的路径时我有点困惑。好吧,这是我在 View 的特定一侧添加直线边框的代码:

 I want this as my output screen

func addRightBorder(with color: UIColor, andWidth borderWidth: CGFloat,view:UIView) {

            let border = UIView()
            border.backgroundColor = color
            border.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
            border.frame = CGRect(x: view.frame.size.width - borderWidth, y: 0, width: borderWidth, height: view.frame.size.height)

            //border.addDashedLine(color: UIColor.red)
            border.addDashedLine(color: UIColor.red)
            view.addSubview(border)
        }*

除了虚线/点线,我怎样才能达到同样的效果?

最佳答案

在我的一个应用程序中,我也需要类似的东西,因此我创建了 UIView Extension。

看看我的代码片段,

extension UIView {
func removeDashedLine() {
    _ = layer.sublayers?.filter({ $0.name == "DashedTopLine" }).map({ $0.removeFromSuperlayer() })
}

func addDashedLine(_ path: UIBezierPath ,pattern : [NSNumber] = [1, 5], color: UIColor = UIColor.red) {

    self.backgroundColor = UIColor.clear

    let shapeLayer: CAShapeLayer = CAShapeLayer()
    let frameSize = self.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.name = "DashedTopLine"
    shapeLayer.frame = shapeRect
    //shapeLayer.position = CGPoint(x: frameSize.width / 2, y: frameSize.height / 2)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color.cgColor
    shapeLayer.lineWidth = 1
    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.lineDashPattern = pattern

    shapeLayer.path = nil
    shapeLayer.path = path.cgPath
    self.layer.insertSublayer(shapeLayer, at: 0)

}
}

它可能无法完全满足您的要求,但应该可以帮助您

关于ios - 如何为 UIView 的任何特定边缘添加虚线边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46174348/

相关文章:

ios - ScrollView 委托(delegate)的冲突参数类型

swift - 将评分添加到值并计算 Firebase 中的平均值

Android:在不同的 Activity 中重复使用相同的 View 对象(案例是关于广告横幅)

swift - 展开 swift 可选类型时,性能会受到什么影响(如果有的话)?

swift - IteratorProtocol 需要 next() 函数来实现通用链表

java - 模糊 TextView 的背景 - IllegalArgumentException 宽度和高度必须 > 0

ios - applicationDidBecomeActive 保持登录状态,类似于 instagram

ios - Storyboard和续集 : How does the presenting VC know when the presented VC dismisses itself?

ios - 安装 GoogleData API 以使用表格

objective-c - UITextView 中的字体大小意外更改