I have added multiple buttons programmatically in my project. I use NSTimer in my viewDidLoad method to call the function to add more buttons every 5 seconds. My problem is I want to clear the buttons from the view which was previously created as new buttons are getting created on top of the old ones.
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector("subtractTime"), userInfo: nil, repeats: true)
}
func subtractTime() {
let button = UIButton(type: UIButtonType.RoundedRect) as UIButton
//button.removeFromSuperview
for var i = 0; i < size; i++ {
for var j = 0; j < size; j++ {
button.frame = CGRectMake(self.x, self.y, BoxWidthHeight, BoxWidthHeight)
button.setTitle("", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
button.tag = tagcounter
self.view.addSubview(button)
}
}
}
I have read that button.removeFromSuperview
should do the work, but i dont get all the buttons removed by it and same remains on the screen.
This should help:
for locView in self.view.subviews {
if locView.isKindOfClass(UIButton) {
locView.removeFromSuperview()
}
}