gpt4 book ai didi

swift - drawRect 不会更新显示

转载 作者:行者123 更新时间:2023-11-28 16:00:37 25 4
gpt4 key购买 nike

有几个关于 drawRect 的问题都帮助了我,但我仍然无法让我的代码工作。

我有一个简单的类,drawExamples:

class drawExamples: UIView {
var shapePosX : CGFloat = 0
var shapePosY : CGFloat = 0

override init(frame: CGRect) {
super.init(frame: frame)
var time1 = NSTimer.scheduledTimerWithTimeInterval(
1,
target: self,
selector: #selector(update),
userInfo: nil,
repeats: true)
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

func update() {
shapePosX = shapePosX + 1
shapePosY = shapePosY + 1
self.setNeedsDisplay()
}

override func drawRect(rect: CGRect) {
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 3.0)
CGContextSetStrokeColorWithColor(context, UIColor.purpleColor().CGColor)

CGContextMoveToPoint(context, shapePosX, shapePosY)
CGContextAddLineToPoint(context, shapePosX + 250, shapePosY + 320)
CGContextAddLineToPoint(context, shapePosX + 300, shapePosY + 320)
CGContextSetFillColorWithColor(context,UIColor.purpleColor().CGColor)
CGContextFillPath(context)
}
}

它最初绘制 View ,但永远不会更新。更新功能运行良好,形状位置更新良好。我假设 setNeedsDisplay 有效,我只是不知道为什么 drawRect 不会重绘我设置的形状。 drawRect 似乎在初始运行后不再被调用

最佳答案

如果你在 Storyboard 中创建 drawExamples 的实例,你必须覆盖

init?(coder aDecoder: NSCoder)

awakeFromNib()

代替

override init(frame: CGRect)

做一个定时器。我更喜欢 awakeFromNib。

所以代码如下。

class drawExamples: UIView {
var shapePosX : CGFloat = 0
var shapePosY : CGFloat = 0

override func awakeFromNib() {
var time1 = NSTimer.scheduledTimerWithTimeInterval(
1,
target: self,
selector: #selector(update),
userInfo: nil,
repeats: true)
}

func update() {
shapePosX = shapePosX + 1
shapePosY = shapePosY + 1
self.setNeedsDisplay()
}

关于swift - drawRect 不会更新显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133733/

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