How to loop through all UIButtons in my Swift view?

前端 未结 9 1263
抹茶落季
抹茶落季 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 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!

提交回复
热议问题