我在项目中以编程方式添加了多个按钮。我在viewDidLoad方法中使用NSTimer来调用该函数,每5秒添加一次按钮。我的问题是我想清除以前创建的视图中的按钮,因为新按钮是在旧按钮之上创建的。
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)
}
}
}
我已经读过button.removeFromSuperview
应该做的工作,但是我没有删除所有按钮,屏幕上也是如此。
答案 0 :(得分:2)
这应该有所帮助:
for locView in self.view.subviews {
if locView.isKindOfClass(UIButton) {
locView.removeFromSuperview()
}
}
答案 1 :(得分:0)
参考,
superview.subviews.forEach ({
if $0 is UIButton {
$0.removeFromSuperview()
}
})