我有一个由线条,形状,文字和图形图像组成的UIView。 通过重新绘制整个图片,应用程序会定期刷新此UIView。但是,当我这样做文本时,行移动到正确的新位置,而图像是重复的。清除子视图似乎不起作用。谁能解释我做错了什么?示例附加代码显示每次触摸时都会重复的图像。
class myMap2: UIView {
var x_value: CGFloat = 100.0
var y_value: CGFloat = 100.0
var text_x = CGFloat(40.0)
var text_y = CGFloat(220.0)
override func drawRect(rect: CGRect) {
for view in self.subviews {
view.removeFromSuperview() // does not execute
print ("removing a subview")
}
self.subviews.forEach({ $0.removeFromSuperview() }) // still not clearing subviews
let draw_context = UIGraphicsGetCurrentContext()
CGContextBeginPath(draw_context)
onDraw(draw_context!)
CGContextStrokePath(draw_context)
UIGraphicsEndImageContext()
let tapRecognizer = UITapGestureRecognizer(target:self, action:"didTap:")
self.addGestureRecognizer(tapRecognizer)
}
func onDraw(ctx: CGContextRef){
let nRect = CGRectMake(text_x , text_y , 250.0, 25.0)
let font1 = UIFont(name: "Courier", size: 8.0)
let nAttr = [
NSFontAttributeName: font1!,
NSForegroundColorAttributeName: UIColor.blackColor()]
let normalLine = "Normal text line. flag at x: \(x_value) y: \(y_value)"
normalLine.drawInRect(nRect, withAttributes:nAttr)
CGContextMoveToPoint(ctx, text_x + 20, text_y + 20 )
CGContextAddLineToPoint(ctx, text_x + 40, text_y + 80)
CGContextAddLineToPoint(ctx, text_x + 175, text_y + 120)
let icon_layer = CALayer()
icon_layer.frame = CGRect(x: x_value, y: y_value, width: 40, height: 40)
let image = UIImage(named: "icon_red_flag")!
icon_layer.contents = image.CGImage
layer.addSublayer(icon_layer)
}
func didTap(gesture: UIGestureRecognizer) {
x_value = x_value + 10
y_value = y_value + 10
text_x = text_x + 10
text_y = text_y + 10
self.setNeedsDisplay()
}
}
答案 0 :(得分:0)
我设法通过保存数组中的每个图层然后删除数组中的每个项目来解决此问题。希望它对某人有所帮助。
Reviewer