IOS/Objective-C: Lazy load UILabel - ios

I am creating a label programatically. Unfortunately, I've discovered that every time I update the label, I am creating a new instance. Is there a way to check if a UILabel already exists before you create it?
This is my current code to create label:
UILabel *percentLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, height, 280, 20)];
If I condition it on following, I get error that it does not recognize label:
for (id percentLabel in self.view.subviews) {
if (![percentLabel isKindOfClass:[UILabel class]]) {
UILabel *percentLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, height, 280, 20)];
}
percentLabel.textAlignment = NSTextAlignmentCenter;
Thanks for any suggestions.

There are many ways to check the object existence. In your example the if statement will create a label on every single iteration of the for cycle. A fixed version of that code will look like this:
UILabel *percentLabel = nil;
for (id subview in self.view.subviews) {
if ([subview isKindOfClass:[UILabel class]]) {
percentLabel = (UILabel *)subview;
break;
}
}
if (!percentLabel) {
// Label creation code here
}
However I would suggest you to store that label as a property in your view controller and initialize it lazily as it shown below:
...
#property (weak, nonatomic) UILabel *percentLabel;
...
- (UILabel *)percentLabel {
if (!_percentLabel) {
UILabel *percentLabel = /* initialization code here */;
// Add percent label as a subview to your view
_percentLabel = percentLabel;
}
return _percentLabel;
}
Note that I'm storing the property with a weak reference, because your view will actually own that label and keep a strong reference via it's subviews property.

It looks to me like you are looping over your subviews (some of which might not actually be labels) and you are trying to change the text alignment.
There are better ways to keep track of a label instance then looping over the subviews every time, such as setting a class property like:
UILabel *labelToChange;
in your interface decleration in your .h file.
Then in your implementation simply access the label using
labelToChange.textAlignment = NSTextAlignmentCenter;
Just make sure you only [UILabel alloc] init once to initialise an instance of UILabel

It would be easier to set a unique tag to your UILabel that way you do not need to check the class. Remember that there are even UILabel in UITableView, UINavigationBar, and so, and you don't want to mess with those.
So, what you should do is create 2 separate methods: one to create label and be called in viewDidLoad ONCE, and another is to update the label.
Create method:
-(void)createLabels {
UILabel *percentLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, height, 280, 20)];
percentLabel.tag = 1111; // a unique tag
[self.view addSubview:percentLabel];
}
Update method:
-(void)updateLabelWithText:(NSString*)newText {
UILabel *yourLabel = (UILabel*)[self.view viewWithTag:1111];
yourLabel.text = newText;
}

you can give percentLabel a unique tag value.
then you can use viewWithTag to get percentLabel, like
UILabel *percentLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, height, 280, 20)];
percentLabel.tag = 100;
[self.view addSubview:percentLabel];
//In another method
UILabel *percenLabel = [self.view viewWithTag:100];
if (percentLabel == nil) {
percentLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, height, 280, 20)];
percentLabel.tag = 100;
percentLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:percentLabel];
}
else {
percentLabel.textAlignment = NSTextAlignmentCenter;
}

Related

Updating A UIView in customView field of UIBarButtonItem

I am keeping a score of a game in the navigation bar.
I am trying to update the UILabel in UIBarButtonItem's customView.
After I call setText on UILabel, it does not get updated.
I tried to change its color just to test, that also does not work.
I tried to update the UILabel by calling setNeedsDisplay
I tried to update the customView in UIBarButtonItem by calling setNeedsDisplay.
Non of that actually updates the view.
I debugged and the code executes and prints the correct value on console when it gets to the line where I NSLog.
I also tried to update the whole view of navController by calling. (Current code does that below)
What is the right way to update/refresh the customView field of UIBarButtonItem
UIBarButtonItem* backUIButton =[view.navigationItem.rightBarButtonItems objectAtIndex:1];// I have 2 items in rightBarButtonList
UIView* settingFrame =backUIButton.customView;
for (UIView *i in settingFrame.subviews){
if([i isKindOfClass:[UILabel class]]){
UILabel *newLbl = (UILabel *)i;
if(newLbl.tag == 1){
/// Write your code
NSString *inStr = [NSString stringWithFormat:#"%ld", [Utility getCoins] ];
NSLog(#"data : %#",inStr);
[newLbl setTextColor:[UIColor redColor]];
[newLbl setText:inStr];
[view.navigationController.view setNeedsDisplay];
}
}
}
Thanks
I will just keep a property of the label
For example
I keep a property
#property (weak,nonatomic)UILabel * numlabel;
Here I create the custom bar item
UIView * customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,80,40)];
UILabel * label = [[UILabel alloc] init];
label.text = #"1";
label.frame = CGRectMake(0,0,80,40);
self.numlabel = label;
[customView addSubview:label];
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:customView];
self.navigationItem.leftBarButtonItem = item;
Then When I need to change
self.numlabel.text = #"2";
I have test with my XCode,it works well
#interface HomeViewController ()
{
UILabel *label;//Globally declare the label to make changes
}
- (void)viewDidLoad
{
[super viewDidLoad];
label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
label.text = #"First";
UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:label];//set label as barButtonItem
self.navigationItem.rightBarButtonItem = barButton;
}
here, i updated the label with a buttonAction
- (IBAction)buttonAction:(id)sender
{
label.text = #"second";//successfully updated the label
}

Accessing UILabel created on run time

I have created UILabel (lblCount) and UIButton (btnAdd) on a UIButton (Add Item Button)'s action method. The new UILabel and UIButton is added to scrollview. The UILabel (lblCount) shows count of UIButton (btnAdd) tapped. Here, addBtnClickCount is an integer which counts the number of click.
UILabel * lblCount = [[UILabel alloc] initWithFrame:CGRectMake( 50, 100*addBtnClickCount, 25, 25)];
lblCount.text = [NSString stringWithFormat:#"%d",count];
lblCount.tag = addBtnClickCount;
lblCount.textColor = [UIColor whiteColor];
lblCount.textAlignment = NSTextAlignmentCenter;
[self.scrollView addSubview:lblCount];
addBtnClickCount = addBtnClickCount+1;
There will be multiple label (lblCount) and button (btnAdd) when user taps Add Item Button. I want to access particular label for particular add button and display the count.
You have already set tag on your label. Create a mutable array labelArray and add label to it. To access the particular label do following code on add button's action.
-(void)addItem:(UIButton*)button{
UILabel* lblShowCount = [_labelArray objectAtIndex:[button tag]];
lblShowCount.text = [NSString stringWithFormat:#"%d", [lblShowCount.text integerValue]+1];
}
Here i understand that #Hem Poudyal, know's that with help of viewWithTag.he will get output. but don't know how to achieved that. so i am describing over here.
Step 1: Here i am adding UILabel and UIButton to self.view instead of UIScrollView. i hope you can convert it as UIScrollView. here i applied some relation between UILabel tag and UIButton tag. that you can see in below code.
for (int i=0; i<10; i++) {
UILabel * lblCount = [[UILabel alloc] initWithFrame:CGRectMake( 50, (i*50)+((i+1)*5), 100, 50)];
lblCount.text = [NSString stringWithFormat:#"%d",0];
lblCount.tag = [[NSString stringWithFormat:#"%d%d",i,i] integerValue];
lblCount.backgroundColor = [UIColor yellowColor];
lblCount.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:lblCount];
UIButton* btnTemp = [UIButton buttonWithType:UIButtonTypeCustom];
btnTemp.tag = i;
btnTemp.backgroundColor = [UIColor redColor];
[btnTemp addTarget:self action:#selector(btnTempClick:) forControlEvents:UIControlEventTouchUpInside];
btnTemp.frame = CGRectMake( 150, (i*50)+((i+1)*5), 100, 50);
[btnTemp setTitle:[NSString stringWithFormat:#"Button : %d",i] forState:UIControlStateNormal];
[self.view addSubview:btnTemp];
}
Step 2: In UIButton selector method, Do the following things.
-(IBAction)btnTempClick:(id)sender{
UIButton* btnInner = sender;
NSInteger lblTagbaseOnButtonTag = [[NSString stringWithFormat:#"%ld%ld",btnInner.tag,btnInner.tag] integerValue];
UILabel* lblReceived = (UILabel*)[self.view viewWithTag:lblTagbaseOnButtonTag];
lblReceived.text = [NSString stringWithFormat:#"%ld",[lblReceived.text integerValue]+1];
}
And Output is :
You should have an array that you add the labels and buttons too (this could be one array containing a dictionary or custom class or multiple arrays). Now, when a button is tapped you can find where it is in the array and get the corresponding label to update.
The cheat way is to set the tag of the buttons and labels so you can find one from the other using viewWithTag:.
You need to set unique tag value while creating the labels and buttons and by using viewWithTag: you can access the respective ui container.

Updating same label with new text in ios

I am trying to update label. When I tap on label the text is move to textview then when i click on Done every time new label is created with updated text. What should I do to update same label? I am using `singleton' for doing so.
Try searching about IBOutlets and properties of particular UI Elements. Like, you want to change your .text property of the UILabel in this case. There is absolutely no use for singletons here.
Try to use viewWithTag to get the existing label if you don't have the instance of label.
For example:
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(10, 60, 200, 100)];
[self.view addSubview:myView];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, CGRectGetWidth(myView.frame), 50)];
[myLabel setTag:1001]; // We can use this tag to find the label from different place.
[myView addSubview:myLabel];
To find the label
UILabel *mLabel = (UILabel *) [myView viewWithTag:1001];
if (mLabel) {
[mLabel setText:#"Hello"];
}

Squeeze the label if there is no data in Lita

On the screen I have a label called namelabel and agelabel. namelabel is set above the agelabel. These two labels' datas are taken from Lita with sqlite. What I want to do is, if there is no name data in Lita, I would like to move the agelabel to the namelabel's position. I have wrote the following code, but it did not work.
//Lita's data table's name is "table".
if(table.age == nil) {
UILabel *agelabel = [[UILabel alloc] initWithFrame: CGRectMake(20,350,100,30)];
agelabel.text = table.age;
[self.view addSubview:agelabel];
} else {
UILabel *namelabel = [[UILabel alloc] initWithFrame: CGRectMake(20,350,100,30)];
namelabel.text = table.name;
[self.view addSubview:namelabel];
UILabel *agelabel = [[UILabel alloc] initWithFrame: CGRectMake(20,370,100,30)];
agelabel.text = table.age;
[self.view addSubview:agelabel];
}
Please help me with dealing this question.
Thank you very much.
I solved this question by writing it as below:
if ([table.age length] == 0){}

viewWithTag and addSubview

I am trying to reuse the label by making a call to viewWithTag when I press the UIButton. The code looks ok when it is executed the first time, but is it leaking on executing it multiple times due to line 7? Also is it just better to remove the label from the superview, alloc and addSubview instead of using viewWithTag?
1. UILabel *label = (UILabel *)[self.view viewWithTag:100];
2. if(label == nil) {
3. label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)] autorelease];
4. label.tag = 100;
5. }
6.
7. [self.view addSubview:label];
Move the code [self.view addSubview:label]; inside your if block. When your if condition is false, that means the label is already part of of your viewcontroller's view hierarchy, so if you add it again like in your original code it will be double retained.
UILabel *label = (UILabel *)[self.view viewWithTag:100];
if (!label) {
label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)] autorelease];
label.tag = 100;
[self.view addSubview:label];
}
If you are using a .xib or storyboard just link it with an IBOutlet.
If you'r using code only, try to save it as a private variable.

Resources