in iOS, is it possible to assign a string ID to UI objects and then retrieve them in the code by that ID?
I am looking for something similar to the Android's findViewById(id)
in iOS, is it possible to assign a string ID to UI objects and then retrieve them in the code by that ID?
I am looking for something similar to the Android's findViewById(id)
you can use viewWithTag
but tag is type of Int
:
let superView = UIView()
let subView = UIView()
subView.tag = 100
superView.addSubview(subView)
let v = superView.viewWithTag(100)
if use xib
or storyboard
you can bind id like this:
use runtime you can bind obj to obj ,but seems not you want :
objc_setAssociatedObject(superView, "key", subView, .OBJC_ASSOCIATION_RETAIN)
let v = objc_getAssociatedObject(superView, "key")
you can use an enum to get the view :
enum UIKey:String {
case AA = "aa"
func findView(byKey:String ,fromView:UIView) -> UIView {
let v :UIView!
switch self {
// get view from real tag value
case .AA: v = fromView.viewWithTag(1)
}
return v
}
}
then use :
let dict = ["aa":123]
dict.forEach { (key,value) in
let v = UIKey(rawValue: key)?.findView(key, fromView: self.view)
//set v with your value
}
Int
type if you want bind obj to obj you can use runtime to do it –
Daddylonglegs xib
or storyboard
is use a @IBOutlet
–
Daddylonglegs As you are having several viewControllers in the storyboard you're probably looking for UIStoryboard
s storyboard.instantiateViewControllerWithIdentifier(identifier: String)
// Basic example
let viewController = yourStoryboard.instantiateViewControllerWithIdentifier("id") as! UIViewController
I needed to share one UITableViewCell descendant with a UIButton across multiple UITableViewControllers. So IBOutlet was not an option for me and I needed something similar to Android findByViewId
So I did it in the UITableViewCell descendant when configure it:
for view in self.contentView.subviews {
if let button = view as? UIButton {
button.setTitle(item.label, for: .normal)
}
}
If you have more complicated cell layout I think you may use some specific view properties to identify the required subview.
P.S. from my experience using the Tag property for such purposes is generally not a good idea.
© 2022 - 2024 — McMap. All rights reserved.