I would like to add multiple UIViews when the user taps the screen I am using the code below and it creates a UIView when I tap but removes the previous one. What am I doing wrong?
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject()! as UITouch
let location = touch.locationInView(self.view)
println(location)
rectangle.frame = CGRectMake(location.x, location.y, 20, 20)
rectangle.backgroundColor = UIColor.redColor()
self.view.addSubview(rectangle)
}
Assuming rectangle
is a property, this code only changes the frame of the existing rectangle and re-adds it to the view hierarchy. If you want a new rectangle to be added each time the user begins touching the device, you have to create a new instance of UIView each time. For example:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject()! as UITouch
let location = touch.locationInView(self.view)
println(location)
let rectangle = UIView(frame: CGRectMake(location.x, location.y, 20, 20))
rectangle.backgroundColor = UIColor.redColor()
self.view.addSubview(rectangle)
}
Additionally, in case this wasn't your intention, the code you're using won't center the new view on the touch location, it's origin will be there, but the view will extent from there to 20 points down and 20 points to the right. If you want the view to be centered in the touch location, I suggest using the view's center property:
let rectangle = UIView(frame: CGRectMake(0, 0, 20, 20))
rectangle.center = location
self.view.addSubview(rectangle)