Daniele B Daniele B - 5 months ago 54
Swift Question

Swift: get UI objects by 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)

Answer

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: enter image description here

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")

update:

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

}