[英]Remove UIButton Programmatically in swift
我在項目中以編程方式添加了多個按鈕。 我在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
應該可以完成工作,但是我沒有將所有按鈕都刪除,並且屏幕上仍然保留着同樣的按鈕。
這應該有助於:
for locView in self.view.subviews {
if locView.isKindOfClass(UIButton) {
locView.removeFromSuperview()
}
}
引用這個
superview.subviews.forEach ({
if $0 is UIButton {
$0.removeFromSuperview()
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.