Everything is a VIEW!

Juan Torres
3 min readJun 15, 2022

In app development, at least in my experience it was very difficult to accept that almost everything is a view or has a view property. Like the View Controllers, the word view is in the name so it has the view property. but other objects like “search bar” where view isn’t in the title, it still takes from UIView Hierarchy. If you go down the rabbit hole, you’ll find that everything just goes all the way down, that it’s all just the same thing. Just repurposed. It’s hard to get used to that fact. Leading me to a mistake I made and would like to share with you so that maybe you won’t make the same mistake. I had a class let’s just call it MainViewController. And for this example it will be very bare code. But let’s add a UISearchBar but it will be a custom class because we don’t want to make the MainViewController to be too crowded.

What I wanted to do so that the code would be cleaner, is add the functions pertaining to the search bar, be in that class. as you can see, I added a tap gesture to the Search Bar class. Tap gestures are generally used on Views. and since everything is a view it accepted the gesture ON THE SEARCH BAR. And if you used an app before, and tapped on the search bar, you know a keyboard pops up and you’re able to text. I thought this would work on the screen that the Search bar was on, not the search bar itself. So what would happen, appeared to be nothing. i would tap away at the search bar, and no keyboard would show, and there was no way to text because, when a tap was registered, the code signals the keyboard to hide instantly. So that code up there doesn’t do what i want it to do, but it definitely works.

So when working with views, all of them, make sure the gestures are placed on the views that the smaller views are on. That might sound confusing if you’re not used to coding in swift. But take this code i have shared with you and test it, and you will notice nothing happens. (BTW, the point of this code is that when you tap away from the search bar, the keyboard will disappear). so Test the code above. But make sure you add the Search bar to the class, and make sure the search bar class is the MSearchBar class. as shown below

If you tested it. you’ll see nothing happens. or that’s what it appears to be.

if you add a break point to where the Dismiss function is. you’ll see it runs. you’ll see that it definitely does something. So instead of adding that tap gesture to that class, it’s better to add it to the main class. Because that’s where you want the dismissal to trigger. So you’d change the code to this. Unfortunately.

Of course there are ways around this with Extentions to classes or even a view. There’s many ways to paint the picture.

--

--