NEW: Master Swift design patterns with my latest book! >>

How to find a UIView subview using viewWithTag()

Written by Paul Hudson    @twostraws

If you need a quick way to get hold of a view inside a complicated view hierarchy, you're looking for viewWithTag() – give it the tag to find and a view to search from, and this method will search all subviews, and all sub-subviews, and so on, until it finds a view with the matching tag number. The method returns an optional UIView because it might not find a view with that tag, so unwrap it carefully.

Here's an example:

if let foundView = view.viewWithTag(0xDEADBEEF) {
    foundView.removeFromSuperview()
}

Easy to remember tags such as 0xDEADBEEF are quite common amongst coders.

NB: Extensive use of viewWithTag() is a sign of code structure. It's good for the occasional shortcut, but really shouldn't be relied on for serious development.

Available from iOS 2.0 – see Hacking with Swift tutorial 25

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Get the ultimate experience

The Swift Power Pack includes my first six books for one low price, helping you jumpstart a new career in iOS development – check it out!

Click here to visit the Hacking with Swift store >>