【问题标题】:Delete buttons previously added删除之前添加的按钮
【发布时间】:2021-09-12 17:14:03
【问题描述】:

我在我的应用程序开始时使用一个类添加了 24 个按钮,用户可以按下其中任何一个或全部。然后按下了“另一个”按钮我想删除所有这 24 个按钮。

添加它们:

for j in 0...2 {
    for i in 0...7 {
        // use the CLASS KSPIckButton to format the buttons
        let buttonOne: UIButton = KSPickButton(frame: CGRect(x: (j + 1) * 28 + (j * 80), y: (i + ii) * 35 + buttonSet, width: 110, height: 30))
            
        // Add the button to the storyboard
        self.view.addSubview(buttonOne)
        
    }
}

如何删除它们?

我想在所有 24 个按钮中使用一个简单的循环 self.view.Remove() 但不知道怎么做?

【问题讨论】:

    标签: ios swift xcode uibutton


    【解决方案1】:

    解决方案 1

    添加标签

    self.buttonOne.tag = 333
    self.view.addSubview(buttonOne)
    

    然后

    self.view.subviews.forEach { 
       if $0.tag == 333 {  
          $0.removeFromSuperview() 
       } 
    }
    

    解决方案 2

    您还可以将它们添加到数组中并通过调用 removeFromSuperview 循环遍历它们

    解决方案 3

    self.view.subviews.forEach { 
       if $0 is KSPickButton {  
          $0.removeFromSuperview() 
       } 
    }
    

    【讨论】:

    • 请注意,使用标签查找视图是脆弱的。将按钮保存到数组中是一个更好的主意。
    猜你喜欢
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    相关资源
    最近更新 更多