viewWithTag and addSubview - ios

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.

Related

IOS/Objective-C: Lazy load UILabel

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;
}

SetLeftView In Label Objective-C

it has been asked before (using textfield, and I'm asking how to include a character not a small icon), and yes I have already tried using this SetLeftView to put a dollar sign '$' or whatever character I want beside the TEXTFIELD.
However, I do not want a textfield, but a label, and when I apply the same code to do what I want, it returns me an error, I mean Xcode fails to build the code.
Here is my code:
// We add a label to the top that will display the results
self.resultLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 80, TEXTAREA_WIDTH, TEXTAREA_HEIGHT)];
[resultLabel setBackgroundColor:[UIColor clearColor]];
[resultLabel setText:#"01234"];
[resultLabel setFont:[UIFont fontWithName:#"AppleGothic" size:30.0f]];
resultLabel.textColor = RGB(255,255,255);
resultLabel.textAlignment = NSTextAlignmentCenter;
// Add it to the view
[self.view addSubview:resultLabel];
UILabel *dollarSignLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 80, 25, 40)];
dollarSignLabel.text = #"$";
dollarSignLabel.textColor = RGB(255,255,255);
[dollarSignLabel setFont:[UIFont fontWithName:#"AppleGothic" size:30.0f]];
[resultLabel setLeftView:dollarSignLabel];
[resultLabel setLeftViewMode:UITextFieldViewModeAlways];
Error: No visible #interface for 'UILabel' declares the selector
'setLeftView'. Same error in the line of setLeftViewMode.
Again, this works if I use a textfield.
My working code (using textfield)
// adding a textField for input
UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(viewHalf-30, 100, 200, 40)];
[myTextField setBackgroundColor:[UIColor clearColor]];
[myTextField setText:#"0"];
[myTextField setFont:[UIFont fontWithName:#"AppleGothic" size:30.0f]];
myTextField.textColor = RGB(255,255,255);
[[self view] addSubview:myTextField];
UILabel *dollarSignLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 25, 40)];
dollarSignLabel.text = #"$";
dollarSignLabel.textColor = RGB(255,255,255);
[dollarSignLabel setFont:[UIFont fontWithName:#"AppleGothic" size:30.0f]];
[myTextField setLeftView:dollarSignLabel];
[myTextField setLeftViewMode:UITextFieldViewModeAlways];
The reason you can't apply that because UILabel doesn't have a method named setLeftView as UITextField do.
What you can do is :
Create two labels next to each other.
Set left labels trailingSpace to right label to 0. Arrange other constraints whatever you want.
Set left label's textAlingment property to NSTextAlignmentRight and right label's to NSTextAlignmentLeft.
Set dolar sign on a left label and numbers to another.
Since a label isn't editable by the user anyway, there is no reason not just to add your $ sign to the label itself.
label.text = [#"$" stringByAppedingString:yourText];
if the special symbol should be an image instead, then look at NSTextAttachment & draw attributed Text
hope this will help u out.
add a dollar image on your label.
override following method of UILabel
-(CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
bounds.origin.x =+leftMargin;
return bounds;
}
- (void)drawTextInRect:(CGRect)rect
{
[super drawTextInRect: CGRectInset(self.bounds, leftMargin , 0)];
}

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.

Scroll UILabel with UITableView

UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
messageLabel.text = CONNECTED;
messageLabel.textColor = [UIColor blackColor];
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = NSTextAlignmentCenter;
[messageLabel sizeToFit];
self.TableView.backgroundView = messageLabel;
The last row of this code set backgroundView to my UILabel but it stays centered and if I scroll the table view, the message position stays fixed. How to solve this problem?
I want that the UILabel to follow the scroll event.
Just add your UILabel as a subview to your tableView and send it back.
[self.TableView addSubview:messageLabel];
[self.TableView sendSubviewToBack:messageLabel];
Now when you scroll the tableView, this view will also get scrolled.
Other code enhancements (Not related to the question)
You can initialize your label like this
UILabel *messageLabel = [[UILabel alloc] initWithFrame:self.view.bounds];
You can see the following tutorials of TableView:
swift: https://www.weheartswift.com/how-to-make-a-simple-table-view-with-ios-8-and-swift/
objective-c: http://www.makemegeek.com/uitableview-example-ios/
Basically,you should add your label inside a cell and it will work.

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"];
}

Resources