NEW: Learn SwiftUI with my free YouTube video series! >>

How to find a UIView subview using viewWithTag()

Swift version: 5.0

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.

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

Available from iOS 2.0 – see Hacking with Swift tutorial 25

Similar solutions…

About the Swift Knowledge Base

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

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns 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 Advanced iOS Volume Two 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 us know!

Average rating: 3.8/5