Remove UIButton Programmatically in swift

与世无争的帅哥 提交于 2019-12-12 06:46:01

问题


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.


回答1:


This should help:

for locView in self.view.subviews {
    if locView.isKindOfClass(UIButton) {
        locView.removeFromSuperview()
    }
}



回答2:


Refer this,

superview.subviews.forEach ({
    if $0 is UIButton {
        $0.removeFromSuperview()
    }
})


来源:https://stackoverflow.com/questions/37342025/remove-uibutton-programmatically-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!