通过标题或 ID 使用 Objective C 在 xcode 中访问使用 UI 构建器创建的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14108579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access elements created with UI builder in xcode with Objective C by title or ID
提问by Osman
I have looked everywhere and I cant seem to figure out how to access elements in my UI in xcode. I know how to change and access elements when I create the UI elements programmatically, but not when I make them using the xcode ui builder.
我到处寻找,但似乎无法弄清楚如何在 xcode 中访问我的 UI 中的元素。当我以编程方式创建 UI 元素时,我知道如何更改和访问元素,但在我使用 xcode ui builder 创建它们时却不知道。
Simply put: Is there a get element by title or something similar (I do not see ID attributes) and if its there please tell me where it is or how to set it.
简单地说:是否有按标题或类似内容的 get 元素(我没有看到 ID 属性),如果有,请告诉我它在哪里或如何设置。
Javascript equivalent of what i am trying to do: document.getElementById('ID');
Javascript 相当于我正在尝试做的事情: document.getElementById('ID');
Java equivalent of what i am trying to do: (EditText)findViewById(ID);
Java相当于我正在尝试做的事情: (EditText)findViewById(ID);
回答by dasblinkenlight
You can get an element by its tag. If you are in a view controller code and you need to get a button that you tagged as 123
in the interface builder, you can use this code:
您可以通过标签获取元素。如果您在视图控制器代码中并且需要获取123
在界面构建器中标记为的按钮,则可以使用以下代码:
UIButton *button123 = [self.view viewWithTag:123];
The element does not need to be a button - it can be any UIView
descendant: a label, a text view, a stepper, or anything else.
元素不需要是按钮——它可以是任何UIView
后代:标签、文本视图、步进器或其他任何东西。
Please note that a more idiomatic way of accessing elements that you create in the interface builder is through IBOutlet
s.
请注意,访问您在界面构建器中创建的元素的更惯用的方式是通过IBOutlet
s。
Here is how you can add an outlet to your view or view controller: open interface builder in a separate window, control-click the element that you want to add as an outlet, find "referencing outlet/new referencing outlet" in the context menu that drops down, and drag from the black circle into the header of your view or view controller. When you drop the item into the code, you will be prompted for the name of the outlet. Once the outlet is created, you can access its corresponding element through the variable that you created.
以下是向视图或视图控制器添加插座的方法:在单独的窗口中打开界面构建器,按住 Control 键单击要添加为插座的元素,在上下文菜单中找到“引用插座/新引用插座”下拉,然后从黑色圆圈拖动到视图或视图控制器的标题中。当您将物品放入代码中时,系统会提示您输入插座的名称。创建插座后,您可以通过您创建的变量访问其对应的元素。