我正在UIContainerView中创建一个下面描述的类的子视图。这些值已正确打印到终端窗口,但在我定义的子视图中并未实际显示。我认为setNeedsDisplay()应该解决这个问题,但是什么也没有出现。
我正在将该子视图创建为let canvas = Canvas()
,并且也尝试过
canvas.setNeedsDisplay()
无效。
class Canvas: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else { return }
context.setStrokeColor(login_theme_color.cgColor)
context.setLineWidth(10.0)
context.setLineCap(.butt)
lines.forEach { (line) in
for(i, p) in line.enumerated(){
//context.move(to: p)
//context.addLine(to: p)
if i == 0 {
context.move(to: p)
print("First point of new line is \(p)")
}else{
context.addLine(to: p)
print("point is \(p)")
}
}
}
context.strokePath()
}
var lines = [[CGPoint]]()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
lines.append([CGPoint]())
//setNeedsDisplay()
}
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()
}
}
为什么这些值会正确打印到终端,但是lines数组实际上不在视图中显示这些值?非常感谢您的帮助。
我使用以下约束定义画布:
let canvas = Canvas()
@objc fileprivate func setupCanvas(){
//canvas.setNeedsDisplay()
containerView.addSubview(canvas)
canvas.translatesAutoresizingMaskIntoConstraints = false
canvas.topAnchor.constraint(equalTo: rectangle2.topAnchor, constant: 74).isActive = true
canvas.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: (view.frame.width/2) + 8).isActive = true
canvas.rightAnchor.constraint(equalTo: rectangle2.rightAnchor, constant: -4).isActive = true
canvas.bottomAnchor.constraint(equalTo: howitWorksText.bottomAnchor, constant: 0).isActive = true
canvas.layer.cornerRadius = 30
canvas.layer.shadowRadius = 0.5
canvas.layer.shadowColor = UIColor.white.cgColor
//canvas.backgroundColor = UIColor.clear
//canvas.layer.borderWidth = 2.0
//canvas.layer.borderColor = UIColor.black.cgColor
canvas.layer.masksToBounds = true
canvas.backgroundColor = .white
//canvas.setNeedsDisplay()
}
并在我的setupCanvas()
中致电ViewDidLoad()
答案 0 :(得分:1)
您的坐标不正确,因为您使用的参考系错误。在location(in view:)
中为视图指定nil
会选择窗口的坐标空间。因此,即使您的触摸是在画布内部,您的图形也不是。您想通过将Canvas
而不是self
传递到nil
来获得location(in:)
视图内的触摸坐标。
在touchesMoved()
中进行更改:
guard let point = touches.first?.location(in: nil) else { return }
收件人:
guard let point = touches.first?.location(in: self) else { return }
有关更多信息,请查看location(in:)
的文档。