LoginSignup
6
6

More than 5 years have passed since last update.

[Swift]subView探索

Last updated at Posted at 2016-02-01

UISearchBarとかで見た目変更したくてsubView探索するときに便利なメソッドを書いた。

extension UIView {
  func searchSubViews<T: UIView>(type: T.Type, findClosure: ((findObject:T) -> Void)) {
    subviews.forEach({
      if let v = $0 as? T {
        findClosure(findObject: v)
      }else{
        $0.searchSubViews(type, findClosure: findClosure)
      }
    })
  }
}

見つけたいクラスを指定すると、findClosureが見つけ次第呼ばれる。

2016/2/29追記

画面上から探す場合

extension UIApplication {
  func searchView<T: UIView>(type: T.Type, findClosure: ((findObject:T) -> Void)) {
    windows.forEach{
      $0.subviews.forEach{v in v.searchSubViews(type, findClosure: findClosure)}
    }
  }
}
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6