How to loop through all UIButtons in my Swift view?

前端 未结 9 1244
抹茶落季
抹茶落季 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: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
            }
        }
    }
    

提交回复
热议问题