· 1 min learn
Discover ways to use string primarily based UIView identifiers as a substitute of tags. In case you are uninterested in tagging views, take a look at these various options.
First method: accessibility to the rescue!
Lengthy story quick, I used to be fairly uninterested in tagging views with silly quantity values, so I regarded for a greater various resolution to repair my drawback. Because it turned out, there’s a property referred to as accessibilityIdentifier
that may do the job.
extension UIView {
var id: String? {
get {
return self.accessibilityIdentifier
}
set {
self.accessibilityIdentifier = newValue
}
}
func view(withId id: String) -> UIView? {
if self.id == id {
return self
}
for view in self.subviews {
if let view = view.view(withId: id) {
return view
}
}
return nil
}
}
I made a easy extension across the UIView class, so now I can use a correct string worth to uniquely establish any view object within the view hierarchy. It’s fairly a pleasant resolution, now I can title my views in a very nice means. As a free of charge storing the title underneath the accessibilityIdentifier will profit your UI assessments. 😉
Second method: utilizing enums
The principle concept is to have an Int primarily based enum for each view identifier, so mainly you should use the tag property to retailer the enum’s rawValue. It’s nonetheless not so good because the one above, nevertheless it’s far more protected than counting on pure integers. 😬
enum ViewIdentifier: Int {
case submitButton
}
extension UIView {
var identifier: ViewIdentifier? {
set {
if let worth = newValue {
self.tag = worth.rawValue
}
}
get {
return ViewIdentifier(rawValue: self.tag)
}
}
func view(withId id: ViewIdentifier) -> UIView? {
return self.viewWithTag(id.rawValue)
}
}
Actually I simply got here up with the second method proper after I copy & pasted the primary snippet to this text, however what the heck, possibly another person will prefer it. 😂
In case you have a greater resolution for this drawback, be at liberty to share it with me.
Associated posts
· 8 min learn
On this article I’ve gathered my high 10 favourite trendy UIKit ideas that I might undoubtedly wish to know earlier than I begin my subsequent mission.
· 5 min learn
Discover ways to construct advanced varieties with my up to date assortment view view-model framework with out the battle utilizing Swift.
· 5 min learn
Do you wish to discover ways to load a xib file to create a customized view object? Nicely, this UIKit tutorial is only for you written in Swift.
· 4 min learn
Just a bit recommendation about creating customized view programmatically and the reality about why kind constructing with assortment views sucks.