7

I'm contemplating writing some helper functions to make it easier to do simple changes to the UI elements in my iPhone NIB. Mainly - I want to access a UILabel, or other element, via its Name in Interface Builder. Is this possible? Is there a smarter approach?

Example

Say I want to make a super simple iPhone app that displays 'Hello World'. I start a new project and then open the NIB and drag a UILabel into my view and give it a 'Name' of 'LblMain'. Now, presuming that I've included my handy helper function, I'd like to assign the label some new text something like this:

[helper setText:@"Hello World" forLabel:@"LblMain"];

-or-

UILabel *ObjTmp = [helper getUILabel:@"LblMain"];
ObjTemp.text = @"Hello World";

Now - the trick is that I didn't add a:

IBoutlet UILabel *ObjLblMain;

anywhere in .h file - I'm just accessing that label dynamically - wouldn't that be nice?!

Now, for simple apps, to add some more labels or images, I could drag them into my NIB, assign them names in that element's inspector window, and then immediately access them inside code without the stuttering & hassle of adding them in the .h file.

Motivation

  • Basically, I'm frustrated that I have to wire every element in my NIB - it's a lot of stuttering and bookkeeping that I'd rather avoid.
  • I could give a design some naming conventions, and they could generate a NIB without needing to be intimate with the implementation.
4

5 回答 5

8

加载对象后,名称 100% 无法访问,我一直认为这也很奇怪。

可以访问的是“标签”,如果您真的想在不定义出口的情况下访问元素,您可以设置(仅限整数)“标签”值,然后在保存标记元素调用的超级视图中viewWithTag:传入相同的整数。不要忘记默认值是“0”所以使用别的东西。

于 2010-02-18T22:56:31.813 回答
4

您绝对可以以编程方式加载 NIB,找到所有对象并查询它们以找出指向什么的对象。看看以编程方式加载 Nib 文件。但问题是 Interface Builder Identity Name 没有暴露在 IB 之外。所以我不确定你会使用什么作为“forLabel”参数。“名称”字段只是为 IB 文档窗口提供便利。它不是NSObject.

于 2010-02-18T22:00:47.397 回答
1

它可以通过元素标签来完成:
假设您有一个名为“yourView”的 UIView xib 文件,并且在其中有 UILabel,您希望无需连线即可访问它。

  1. 在“yourView”xib 文件中为 UILabel 设置标签,假设您将 UILabel 标签设置为 100。
  2. 在任何地方加载“yourView”后,您无需使用此代码进行任何接线即可获得 UILabel。
    UILabel* yourlabel =(UILabel*) [yourView viewWithTag: 100]; //do whatever you want to your label.
于 2014-05-28T12:36:43.117 回答
0

对于 iOS6+,您可以使用 restoreId 代替 tag,使其更具“可读性”,例如,您可以在 nib 文件和恢复 id 中设置相同的名称。

如果您不想将 nib 中的所有插座链接到视图控制器,您仍然可以通过在当前视图子视图树中搜索来访问它们。请注意,子视图排列是一棵树(您可以在 nib 文件中看到的同一棵树),因此如果您有嵌套视图,则需要进行一些递归。

例如:

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

在您的 nib 文件中,您应该有一个 restoreId 等于“myNibButtonView”的按钮,您可以在身份检查器中找到 restoreId 文本字段(实用程序的第三列)

如果您有大量的网点并且不想将它们全部链接起来,您可以使用它。

于 2014-09-30T13:53:24.360 回答
0

我认为您可以尝试在某些外部编辑器中将 xib 打开为 XML 并查看编译器如何看待它,然后您可能会这样做

于 2011-10-14T02:25:52.173 回答