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){}
Related
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;
}
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
}
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.
I want to add a Label and an Image in titleView of my NavigationItem. I am adding UILabel and UIImageView to a UIView and setting it as titleView of the navigation Item. Things are being added, but I am not able to calculate the length of label and place image next to it.
My code is :-
// Title Name + Image
UIView *titView = [[UIView alloc] initWithFrame:self.navigationItem.titleView.bounds];
self.navigationItem.titleView = titView;
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(-10, -20, 150, 30)];
title.text = #"Bunny ";
[title setTextColor:[UIColor orangeColor]];
[titView addSubview:title];
float x2 = 30; //+ title.bounds.size.width;
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"return" ]];
img.frame = CGRectMake(x2, -20, img.bounds.size.width, 30);
[titView addSubview:img];
I am looking for some way to calc the width text and set accordingly the width of the label. Right now I have set the width of the label as 150. And secondly, calc the x position to place the image just next to the label.
Tried many ways, but nothing works as expected. How can I achieve this ? Can you he give some guidelines such that regardless of length of text of label, things works as expected and UIView gets placed in the center of navigation item.
Any help is highly appreciated. Thanks.
You can call
[title sizeToFit];
after setting its properties and it will size itself to match the contained string.
Set the imageViews x origin to
CGRectGetMaxX(title.frame) + desiredSpacing;
And it could help to subclass UIView to achieve the final results by overwriting layoutSubviews and placing your views there, since the titleView's frame can be adjusted by the navigationBar...basically like this:
#implementation TitleView{
UILabel *_titleLabel;
UIImageView *_img;
}
- (id)initWithTitle:(NSString *)title andImage:(UIImage *)image
{
self = [super init];
if (self) {
_titleLabel = [[UILabel alloc] init];
_titleLabel.text = title;
[_titleLabel setTextColor:[UIColor orangeColor]];
[_titleLabel sizeToFit];
[self addSubview:_titleLabel];
_img = [[UIImageView alloc] initWithImage:image];
[self addSubview:_img];
}
return self;
}
- (void)layoutSubviews{
CGFloat spacingBetweenTextAndImage = 0;
CGFloat width = CGRectGetWidth(_titleLabel.frame)+CGRectGetWidth(_img.frame)+spacingBetweenTextAndImage;
CGFloat x = (CGRectGetWidth(self.bounds)-width)/2;
_titleLabel.frame = CGRectMake(x, (CGRectGetHeight(self.bounds)-CGRectGetHeight(_titleLabel.bounds))/2, CGRectGetWidth(_titleLabel.bounds), CGRectGetHeight(_titleLabel.bounds));
x+=CGRectGetWidth(_titleLabel.bounds)+spacingBetweenTextAndImage;
_img.frame = CGRectMake(x, (CGRectGetHeight(self.bounds)-CGRectGetHeight(_img.bounds))/2, CGRectGetWidth(_img.bounds), CGRectGetHeight(_img.bounds));
}
#end
use in your viewController:
UIView *titleView = [[TitleView alloc] initWithTitle:#"Bunny" andImage:[UIImage imageNamed:#"return" ]];
self.navigationItem.titleView = titleView;
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.