开发者

Xcode Adding a label, and setting the text

I am extremely new to objective c development. I used a tutorial to learn how to add a label at run time, but I'm a little confused how to reference it later.

If I add...

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMa开发者_JAVA技巧ke(50, 100, 200, 100)];
myLabel.text = @"My Label";
[self.view addSubview:myLabel];

...in my viewDidLoad method, how can I reference that label from another method on a separate occasion? Unlike C#, I don't name the label for later reference -- so I can't simply reference the name to set it.


You have to declare an instance variable for the label in your class's @interface (and optionally also a property for the ivar). Then assign the label to the ivar/property in viewDidLoad and you can use it later in every other method of the class.

Don't forget to release the label in your -dealloc method. The code in your question leaks memory.


  1. You can hold on to a reference to the UILabel with an ivar.
  2. You can search the UIView for the tag with: -viewWithTag method. Providing you set the tag property before release it. :-)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜