设置需求显示不起作用



我正在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()
}
}

为什么值会正确打印到终端,而线条数组实际上并没有在视图中显示值?提前非常感谢您的帮助。

我使用以下约束来定义我的画布:

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()
}

并在我的ViewDidLoad()中打电话给setupCanvas()

您的坐标已关闭,因为您使用了错误的参考系。 指定location(in view:)中的视图nil将选择窗口的坐标空间。 因此,即使您的触摸在画布内,您的绘图也不会。 您希望通过传递self而不是nil来获取Canvas视图中的触摸坐标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:)的文档。

最新更新