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

How to find a UIView subview using viewWithTag()

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.

Download for free!

Want a free 75-minute video teaching functional programming, protocol-oriented programming, and more? This is your lucky day!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>