gpt4 book ai didi

swift - SetNeedsDisplay 无效

转载 作者:行者123 更新时间:2023-11-28 13:30:10 26 4
gpt4 key购买 nike

我正在 UIContainerView 中创建 subview ,它属于下面描述的类。这些值正确地打印到终端窗口,但实际上并没有显示在我定义的 subview 中。我认为 setNeedsDisplay() 应该解决这个问题,但什么也没有出现。

我将此 subview 创建为 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()
}

}

为什么值会正确地打印到终端,但行数组实际上并没有在 View 中显示值?非常感谢您的帮助。

我使用以下约束定义我的 Canvas :

    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:) 中的 View 指定 nil选择窗口的坐标空间。因此,即使您的触摸在 Canvas 内,您的绘图却不在。您想通过将 self 而不是 nil 传递给 location(in:) 来获取 Canvas View 内部的触摸坐标

touchesMoved() 中更改:

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

到:

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

有关更多信息,请查看 location(in:) 的文档.

关于swift - SetNeedsDisplay 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57517862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com