在 Swift 4 中绘制多条线

Draw multiple lines in Swift 4

在Swift 4中,使用Xcode IDE,我可以很容易地用下面的方法画一个圆:

let circlePath = UIBezierPath(arcCenter: CGPoint(
    x: 100,
    y: 100),
    radius: 50,
    startAngle: CGFloat(0),
    endAngle:CGFloat(Double.pi * 2),
    clockwise: true)

let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath

shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 2.0

但是,我想从A点到B点画一条线,而不是画一个圆。我可以按照此处的示例代码画一条线:https://www.youtube.com/watch?v=9sJxtzTo8W0

为了使线条与示例中的显示方式相同,我需要更改主故事板中的视图。

Is there a way to simply draw a line on the fly, in the same way that I can draw a circle on the fly?

当然,只需使用 addLine(to:) 创建一个 UIBezierPath,然后在您的 CAShapeLayer 中使用以下 path,就像您在示例中对圆所做的那样:

let startPoint = CGPoint(x: 10, y: 10)
let endPoint = CGPoint(x: 20, y: 5)

let linePath = UIBezierPath()
linePath.move(to: startPoint)
linePath.addLine(to: endPoint)

let shapeLayer = CAShapeLayer()
shapeLayer.path = linePath.cgPath

shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 2

view.layer.addSublayer(shapeLayer)

Why does the circle render without me needing to define a class object, but the line requires me to define a class object?

该行不要求您定义 class 对象。这只是另一种方法,您可以使用 CAShapeLayer 技术或 UIView subclass 技术来绘制直线和圆(以及您想要的任何其他类型的形状)。他们都工作得很好。

A UIView subclass 方法,你首先定义你的 class:

class LineView: UIView {

    var startPoint: CGPoint? { didSet { setNeedsDisplay() } }
    var endPoint: CGPoint?   { didSet { setNeedsDisplay() } }

    override func draw(_ rect: CGRect) {
        guard let startPoint = startPoint, let endPoint = endPoint else { return }

        let linePath = UIBezierPath()
        linePath.move(to: startPoint)
        linePath.addLine(to: endPoint)
        linePath.lineWidth = 2

        UIColor.black.setStroke()
        linePath.stroke()
    }
}

然后实例化一个并将其添加到您的视图层次结构中:

let lineView = LineView()
lineView.backgroundColor = .lightGray
lineView.translatesAutoresizingMaskIntoConstraints = false
lineView.startPoint = CGPoint(x: 10, y: 10)
lineView.endPoint = CGPoint(x: 20, y: 5)
view.addSubview(lineView)

NSLayoutConstraint.activate([
    lineView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
    lineView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
    lineView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
    lineView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -10)
])

Does this mean that I can only have 1 type of custom class in my entire project that is viewable at any given time?

就像您可以添加任何您想要的 shapelayer 一样,您可以添加您自己的自定义 UIView subclasses 并添加任意数量。所以理论上你可以有几个 subclass 类型,一个用于不同类型的形状(圆形,直线,圆角矩形,等等)并实例化它们并将它们作为子视图添加到你想要的任何场景的任何视图。