How to loop through all UIButtons in my Swift view?

前端 未结 9 1262
抹茶落季
抹茶落季 2021-02-05 05:22

How would I loop through all UIButtons in my view in Swift? I would want to set all the titles to \"\", but my for-loop in Swift is giving an error.

相关标签:
9条回答
  • 2021-02-05 05:57

    Used some of the offered questions out there and created my own. I believe is the most efficient when you want to programmatically set up the title of various UIButtons(in my case I am building a quiz)

    By randomising my array list and with just a for loop I printing the item at index to the button title

    for view in self.viewForButtons.subviews{
            if view.isKindOfClass(UIButton)
            {
                let button : UIButton = view as! UIButton
                button.setTitle("item[i]", forState: .Normal)
            }
        }
    
    0 讨论(0)
  • 2021-02-05 05:59

    To add some context for a common use case, suppose the buttons were in a scroll view and you wanted to highlight the tapped button and de-highlight the other buttons. In this situation, you would direct all buttons to one action method:

    @objc private func buttonAction(_ button: UIButton) {
        for case let b as UIButton in view.scrollView.subviews {
            if b == button {
                b.setTitleColor(UIColor.green, for: []) // highlight
            } else {
                b.setTitleColor(UIColor.black, for: []) // de-highlight
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-05 06:01

    If you have UIView's within self.view then you need to loop through the subviews while searching for UIButton. Using the accepted answer, I made this little function to do so:

    Swift 4 + :

    func findButton(`in` view: UIView){
        for view in view.subviews as [UIView] {
            if let button = view as? UIButton {
                // Do something with 'button'
            }else{
                // Loop through subview looking for buttons
                findButton(in: view)
            }
        }
    }
    

    Usage:

    override func viewDidLoad() {
        findButton(in: self.view)
    }
    

    Hope this helps!

    0 讨论(0)
  • 2021-02-05 06:10

    This code should work:

    for view in self.view.subviews as [UIView] {
        if let btn = view as? UIButton {
            btn.setTitleForAllStates("")
        }
    }
    

    You need to iterate through the subViews array.

    0 讨论(0)
  • 2021-02-05 06:12

    Here's a short way in Swift if you know the subview only has buttons:

    myView.subviews.map {
      ($0 as? UIButton)!.enabled = false
    }
    
    0 讨论(0)
  • 2021-02-05 06:16

    Swift 4:

    let subviewButtons = self.view.subviews.filter({$0.isKind(of: UIButton.self)})
    
    for button in subviewButtons {
        //do something        
    }
    
    0 讨论(0)
提交回复
热议问题