How can I programmatically access UI elements in a NIB without 'wiring' them?

ε祈祈猫儿з 提交于 2019-12-04 04:14:28

You can definitely load the NIB programmatically, find all the objects and query them to work out what points to what. Just look at Loading Nib Files Programmatically. But the problem is that the Interface Builder Identity Name isn't exposed outside of IB. So I'm not sure what you would use as the "forLabel" parameter. The "Name" field is just a convenience for the IB document window. It's not a property on NSObject.

Name is 100% not accessible after the object is loaded, something I always thought was odd too.

What is accessible is "tag", if you really want to access an element without defining an outlet you can set the (integer only) "tag" value, and then within the superview that holds the tagged element call viewWithTag: passing in the same integer. Don't forget the default is "0" so use something else.

It can be done by the element tag:
Lets say you have UIView xib file called "yourView" and inside it there is UILabel that you want to access it without wiring.

  1. Set a tag to the UILabel in "yourView" xib file, lets assume you set UILabel tag to 100.
  2. After loading "yourView" anywhere you can get UILabel without having any wiring by using this code.
    UILabel* yourlabel =(UILabel*) [yourView viewWithTag: 100]; //do whatever you want to your label.

I think you can try opening the xib in some external editor as XML and see how the compiler sees it, then you might possibly do the same way

For iOS6+ you can use restorationId instead of tag, to make it more "readable", for example you can set the same name in your nib file and in restoration id.

If you do not want to link all the outlets from your nib to your viewcontroller, you still can access them by searching in your current view subviews tree. Note that subviews arrangement is a tree (the same tree that you can see in your nib file), so you will need to do some recursion if you have nested views.

For example:

UIButton *nibButtonView = nil;
for (UIView *view in [self.view subviews]){
    if ([view.restorationIdentifier isEqualToString:@"myNibButtonView"]){
        nibButtonView = (UIButton *)view;
    }
}
[nibButtonView setTitle:@"Yeah" forState:UIControlStateNormal];

In your nib file you should have a button with a restorationId equals to "myNibButtonView", you can find the restorationId textfield in your identity inspector (third column of utilities)

You may use this if you have a huge number of outlets a you don't want to linked them all.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!