【问题标题】:Remove UIButton Programmatically in swift快速以编程方式删除 UIButton
【发布时间】:2016-05-20 08:43:02
【问题描述】:

我在我的项目中以编程方式添加了多个按钮。我在 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 应该可以完成这项工作,但我没有将所有按钮都删除,并且屏幕上仍然存在。

【问题讨论】:

  • 删除按钮的代码在哪里?
  • 你为删除按钮写了什么?

标签: swift uibutton ios9


【解决方案1】:

这应该会有所帮助:

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

【讨论】:

  • 嗨@harshal,如果这个或任何答案解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
【解决方案2】:

参考这个,

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

【讨论】:

    猜你喜欢
    • 2016-07-27
    • 2015-02-13
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 2014-04-18
    • 1970-01-01
    相关资源
    最近更新 更多