以编程方式约束时,uiview 不绘制

uiview not drawing when constrained programmatically

我的代码试图调用一个 class 来控制所有绘图属性,但 uiview 上没有显示任何内容。就像 class 没有被调用,但我知道它被调用了。我不知道该怎么办。重要的是 canvas 覆盖特定区域而不是整个视图,这就是我编程限制它的原因。

var canvas = Canvas()

override func viewDidLoad() {
    super.viewDidLoad()

    canvas.backgroundColor = .black
    setupLayout()
    canvas.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(canvas)

    NSLayoutConstraint.activate ([
          canvas.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :150),
          canvas.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 0),
          canvas.widthAnchor.constraint(equalToConstant: 300),
          canvas.heightAnchor.constraint(equalToConstant: 300),
    ])
}


class Canvas: UIView {

// public function
func undo() {
    _ = lines.popLast()
    setNeedsDisplay()
}

func clear() {
    lines.removeAll()
    setNeedsDisplay()
}

fileprivate var lines = [[CGPoint]]()

override func draw(_ rect: CGRect) {
    super.draw(rect)

    guard let context = UIGraphicsGetCurrentContext() else { return }

    context.setStrokeColor(UIColor.red.cgColor)
    context.setLineWidth(5)
    context.setLineCap(.butt)

    lines.forEach { (line) in
        for (i, p) in line.enumerated() {
            if i == 0 {
                context.move(to: p)
            } else {
                context.addLine(to: p)
            }
        }
    }

    context.strokePath()
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    lines.append([CGPoint]())
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let point = touches.first?.location(in: nil) else { return }
    guard var lastLine = lines.popLast() else { return }
    lastLine.append(point)
    lines.append(lastLine)
    setNeedsDisplay()
}}

更改以下行

guard let point = touches.first?.location(in: nil) else { return }

至此

guard let point = touches.first?.location(in: self) else { return }

存储在 lines 数组中的点对应于您的 CanvasView 附加到的超级视图。需要存储CanvasView对应的点。这正是 self 参数代替上面的 nil 所做的。