Because right now, viewWithTag
actually search for itself first, and then all subviews recursively down the whole subtree, for a view with that tag.
But what if I set the tags of the subviews to 100, 101, etc, and later on, look for tag 100, but the parent of this current view sets the current view's tag to 100? Then viewWithTag
will return the current view instead of any subview.
It is also strange that if the code is
[fooView viewWithTag: 123]
why would the code want to search the subtree including fooView itself? It is like, the code doesn't know fooView good enough to want to search for it too. Or put it another way, fooView
is told to search itself... which is strange. A view doesn't know itself? (need to do a search to look for itself?)
So is there a way to search for subviews and grand-subviews only (without searching for self)?
let result = view.subviews.filter{$0.tag == tag}.first
After reviewing the documentation for
-viewWithTag:
and running a few tests, it appears the answer to OP's question is - This behavior is already provided.I am concluding this to mean that 'view' is also a 'subview', thus limiting the scope of the search.
For 1 level:
To search a view hierarchy with multiple levels:
Take advantage of the recursive nature of
-viewWithTag:
Edit: this will drill down farther than "grand-subviews": it will get any view within the hierarchy that is not self. Also this is to be implemented in a category on
UIView
.do this:
To find specific like UIButton or any UIElement then like this: