How to add multiple UILabels programmatically in Xcode? - ios

Hello in Xcode I am trying to add two labels to my image programmatically but when I add the second one it will overwrite my first one. Here is my code:
//first label
UILabel* caption = [[UILabel alloc] initWithFrame:
CGRectMake(-25, 0, 320, 50)
];
caption.backgroundColor = [UIColor whiteColor];
caption.textColor = [UIColor blackColor];
caption.textAlignment = UITextAlignmentLeft;
caption.font = [UIFont systemFontOfSize:16];
caption.text = [NSString stringWithFormat:#" #%#",[data objectForKey:#"username"]];
[self addSubview: caption];
//second label
UILabel* bottomBox = [[UILabel alloc] initWithFrame:
CGRectMake(-25, -200, 320, 50)
];
caption.backgroundColor = [UIColor whiteColor];
caption.textColor = [UIColor blackColor];
caption.textAlignment = UITextAlignmentCenter;
caption.font = [UIFont systemFontOfSize:16];
caption.text = [NSString stringWithFormat:#" Testing"];
[self addSubview: bottomBox];
I've tried changing the "0 to -200 to modify the Y coordinates so that the second label will shift down but it just overwrites the first one for some reason. Any help would be greatly appreciated thanks.

All the code for your 2nd label is referencing the 1st variable caption instead of bottomBox. You want:
//second label
UILabel* bottomBox = [[UILabel alloc] initWithFrame:CGRectMake(20, 200, 320, 50)];
bottomBox.backgroundColor = [UIColor whiteColor];
bottomBox.textColor = [UIColor blackColor];
bottomBox.textAlignment = UITextAlignmentCenter;
bottomBox.font = [UIFont systemFontOfSize:16];
bottomBox.text = #"Testing";
[self addSubview: bottomBox];

Related

Create UIView programmatically with Objective-C to work in both portrait and landscape

I've to create a view in objective c with two labels on it, label1 has single line and label2 is multi line based on content.
Based on content in the labels I want to adjust view height how can I do that?
Width of the view should be 20 left and right to screen width with below code I can show in portrait but in landscape it was not coming properly, It crops on the right side. How can I do show that right 20 for landscape?
Portrait
Landscape
UIView *emptyTreeView = [[UIView alloc] initWithFrame:CGRectMake(20,20,self.view.frame.size.width - 40,400)];
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(30.0, 30.0, self.view.frame.size.width - 100, 30.0)];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(30.0, 90.0, self.view.frame.size.width - 100, 100.0)];
emptyTreeView.backgroundColor=[UIColor blueColor];
label1.backgroundColor = [UIColor redColor];
label1.textAlignment = NSTextAlignmentCenter;
label1.textColor = [UIColor blackColor];
label1.font = [UIFont boldSystemFontOfSize:18];
label1.numberOfLines = 0;
label1.text = #"The Page Cannot be displayed.";
label2.backgroundColor = [UIColor whiteColor];
label2.textAlignment = NSTextAlignmentCenter;
label2.textColor = [UIColor grayColor];
label2.font = [UIFont systemFontOfSize:15];
label2.numberOfLines = 0;
label2.text = #"Please use this feature or contact your internal contact person directly.";
[emptyTreeView addSubview:label1];
[emptyTreeView addSubview:label2];
[self.view addSubview:emptyTreeView];
Am I doing anything wrong?
A few observations:
Do not add subviews in viewDidLayoutSubviews. That is only for adjusting frame values.
If you refer to self.view, reference its bounds, not its frame. The former is for coordinates of subviews within self.view. The latter is in the coordinate system of its superview (which might not introduce any differences right now, but is just the wrong coordinate system.
If you want the view to resize on rotation, set its autoresizingMask, e.g.
emptyTreeView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
Or
emptyTreeView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
Nowadays, setting frame values and autoresizing masks is a bit of an anachronism. We would generally use constraints, e.g.
- (void)viewDidLoad {
[super viewDidLoad];
UIView *emptyTreeView = [[UIView alloc] init];
UILabel *label1 = [[UILabel alloc] init];
UILabel *label2 = [[UILabel alloc] init];
emptyTreeView.backgroundColor = [UIColor blueColor];
label1.backgroundColor = [UIColor redColor];
label1.textAlignment = NSTextAlignmentCenter;
label1.textColor = [UIColor blackColor];
label1.font = [UIFont boldSystemFontOfSize:18];
label1.numberOfLines = 0;
label1.text = #"The Page Cannot be displayed.";
label2.backgroundColor = [UIColor whiteColor];
label2.textAlignment = NSTextAlignmentCenter;
label2.textColor = [UIColor grayColor];
label2.font = [UIFont systemFontOfSize:15];
label2.numberOfLines = 0;
label2.text = #"Please use this feature or contact your internal contact person directly.";
[emptyTreeView addSubview:label1];
[emptyTreeView addSubview:label2];
[self.view addSubview:emptyTreeView];
emptyTreeView.translatesAutoresizingMaskIntoConstraints = false;
label1.translatesAutoresizingMaskIntoConstraints = false;
label2.translatesAutoresizingMaskIntoConstraints = false;
[NSLayoutConstraint activateConstraints:#[
[emptyTreeView.leftAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leftAnchor constant:20],
[emptyTreeView.rightAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.rightAnchor constant:-10],
[emptyTreeView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:20],
[label1.leftAnchor constraintEqualToAnchor:emptyTreeView.leftAnchor constant:20],
[label1.rightAnchor constraintEqualToAnchor:emptyTreeView.rightAnchor constant:-20],
[label1.topAnchor constraintEqualToAnchor:emptyTreeView.topAnchor constant:20],
[label2.leftAnchor constraintEqualToAnchor:emptyTreeView.leftAnchor constant:20],
[label2.rightAnchor constraintEqualToAnchor:emptyTreeView.rightAnchor constant:-20],
[label2.topAnchor constraintEqualToAnchor:label1.bottomAnchor constant:20],
[emptyTreeView.bottomAnchor constraintEqualToAnchor:label2.bottomAnchor constant:20]
]];
}
Note the translatesAutoresizingMaskIntoConstraints is false and the constraints.

Adjust frame of UITableView Background View?

I am setting a label inside of an empty table view's background view, which is placing the label in the middle of the tableview.
I'd like to move that label up a bit, so it's near the top of the table view, however the code below isn't working:
UILabel *messageLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 20)];
messageLbl.text = #"NO REGISTRATIONS FOUND";
messageLbl.font = [UIFont fontWithName:#"Sansation-Bold" size:20.0f];
messageLbl.textColor = [UIColor lightGrayColor];
messageLbl.textAlignment = NSTextAlignmentCenter;
[messageLbl sizeToFit];
//set back to label view
self.tableView.backgroundView = messageLbl;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.backgroundView.frame = CGRectMake(0, 0, self.tableView.bounds.size.width, 100);
Another easy solution is to add your messageLbl to tableHeaderView:
UILabel *messageLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 50)];
messageLbl.text = #"\n\n NO REGISTRATIONS FOUND";
messageLbl.font = [UIFont fontWithName:#"Sansation-Bold" size:20.0f];
messageLbl.textColor = [UIColor lightGrayColor];
messageLbl.textAlignment = NSTextAlignmentCenter;
messageLbl.numberOfLines = 0;
[messageLbl sizeToFit];
//set back to label view
self.tableView.tableHeaderView = messageLbl;
Quick solution is just by adding \n at the end the of text and set no of lines to 0. Try this
messageLbl.numberOfLines = 0;
messageLbl.text = #"NO REGISTRATIONS FOUND\n\n\n\n";
Looks like you were hiding the Y axis behind Navigation bar
try it by setting some Y axis height & Don't forget to add SubView
UILabel *messageLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, self.tableView.bounds.size.width, 20)];
messageLbl.text = #"NO REGISTRATIONS FOUND";
messageLbl.font = [UIFont fontWithName:#"Sansation-Bold" size:20.0f];
messageLbl.textColor = [UIColor lightGrayColor];
messageLbl.textAlignment = NSTextAlignmentCenter;
[messageLbl sizeToFit];
//set back to label view
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[self.view addSubview: messageLbl];

Progress in label

Use code for show downloading progress in percent
float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
NSString *percentage = [NSString stringWithFormat:#"%d%%", (int)((progress/total)*100)];
[_label setText:[NSString stringWithFormat:#"%#%%", percentage]];
_label = [[UILabel alloc]initWithFrame:CGRectMake(323.43, 148.84, 42, 19)];
[_label setText: percentage];
_label.numberOfLines = 1;
_label.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
_label.adjustsFontSizeToFitWidth = YES;
_label.minimumScaleFactor = 10.0f/12.0f;
_label.clipsToBounds = YES;
_label.backgroundColor = [UIColor blackColor];
_label.textColor = [UIColor whiteColor];
_label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:_label];
If I use _label.backgroundColor = [UIColor blackColor]; progress label work correctly. But if I use _label.backgroundColor = [UIColor clearColor]; numbers superimposed on each other
Why?
_label.backgroundColor = [UIColor blackColor];
_label.backgroundColor = [UIColor clearColor];
You are adding multiples labels with the method [self.view addSubview: _label] If you want to see that more visually use the Debug View Hierarchy when you are debugging.
To solve the issue you can check if the _label is not nil and you will set only the text. See the code below:
float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
float total = [[NSNumber numberWithInteger:totalBytesExpectedToWrite] floatValue];
NSString *percentage = [NSString stringWithFormat:#"%.f%%", ((progress / total) * 100)];
if (!_label) {
_label = [[UILabel alloc] initWithFrame:CGRectMake(323.43, 148.84, 42, 19)];
_label.numberOfLines = 1;
_label.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
_label.adjustsFontSizeToFitWidth = YES;
_label.minimumScaleFactor = 10.0f/12.0f;
_labellabel.clipsToBounds = YES;
_label.backgroundColor = [UIColor blackColor];
_label.textColor = [UIColor whiteColor];
_label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:_label];
}
_label.text = percentage;
Notice that you are trying to set the text before initialize it: [_label setText:[NSString stringWithFormat:#"%#%%", percentage]]; and if _label is nil the app crash in that point.
Try to avoid set the frame manually instead of that use auto layout.
You appear to be adding multiple labels [self.view addSubview: _label]. This code should only be executed once. With a black background you can only see the topmost label. With a clear background you can see them all
I think, the Label have overlapped. So you can use "tag" value to remove the label and recreated it every time.
Adding Tag
_label = [[UILabel alloc] initWithFrame:CGRectMake(323.43, 148.84, 42, 19)]; // after you will set the tag for the required Label.
_label.tag = 505;
Remove and recreate the label
[[self.view viewWithTag:505]removeFromSuperView]; // after you will create the Label
_label = [[UILabel alloc] initWithFrame:CGRectMake(323.43, 148.84, 42, 19)];

How to align custom UINavigationBar title (UILabel )in middle (iOS)

I am using following code to align 2 strings in UINavigationBar centre .
for ex:
<Back John Kelly Maria
23/F
I need these kind of middle aligned text in UINavigationbar but what jam now getting is all the text aligned in right side of UINavigationBar .
something like this
<Back John Kelly Maria
23/F
Please help..me .
this is my code
UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,50)];
UIFont * customFont = [UIFont fontWithName:#"Helvetica Neue" size:19]; //custom font
NSString * text =title;
UILabel *patientNameLabel;
if([title length]>15){
patientNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,320,30)];
}else{
patientNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,320,30)];
}
patientNameLabel.text = #"John Kelly Maria";
patientNameLabel.font = customFont;
patientNameLabel.numberOfLines = 0;
patientNameLabel.textAlignment=NSTextAlignmentCenter;
patientNameLabel.minimumScaleFactor = 10.0f/12.0f;
patientNameLabel.clipsToBounds = YES;
patientNameLabel.backgroundColor = [UIColor clearColor];
patientNameLabel.textColor = [UIColor blackColor];
patientNameLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight;
NSString *subTitle =subTitleText;
UIFont * customFont1 = [UIFont fontWithName:#"Helvetica Neue" size:14]; //custom font
UILabel *subTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,25,320,20)];
subTitleLabel.textAlignment = NSTextAlignmentCenter;
subTitleLabel.text = #"23/F";
subTitleLabel.font = customFont1;
subTitleLabel.textAlignment=NSTextAlignmentCenter;
subTitleLabel.numberOfLines = 1;
subTitleLabel.adjustsFontSizeToFitWidth = YES;
subTitleLabel.minimumScaleFactor = 10.0f/12.0f;
subTitleLabel.clipsToBounds = YES;
subTitleLabel.backgroundColor = [UIColor clearColor];
subTitleLabel.textColor = [UIColor blackColor];
[titleView addSubview:patientNameLabel];
[titleView addSubview:subTitleLabel];
Add below two lines before addSubview lines..
patientNameLabel.center = CGPointMake(titleView.frame.size.width/2, 0);
subTitleLabel.center = CGPointMake(titleView.frame.size.width/2, 25);
Add Below Code & see
UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,50)];
UIFont * customFont = [UIFont fontWithName:#"Helvetica Neue" size:19]; //custom font
NSString * text =#"Nilesh Patel";
UILabel *patientNameLabel;
if([text length]>15){
patientNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,320,30)];
}else{
patientNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,320,30)];
}
patientNameLabel.text = #"Nilesh Patel";
patientNameLabel.font = customFont;
patientNameLabel.numberOfLines = 0;
patientNameLabel.textAlignment=NSTextAlignmentCenter;
patientNameLabel.minimumScaleFactor = 10.0f/12.0f;
patientNameLabel.clipsToBounds = YES;
patientNameLabel.backgroundColor = [UIColor clearColor];
patientNameLabel.textColor = [UIColor blackColor];
patientNameLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight;
NSString *subTitle =#"iOS Developer";
UIFont * customFont1 = [UIFont fontWithName:#"Helvetica Neue" size:14]; //custom font
UILabel *subTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,25,320,20)];
subTitleLabel.textAlignment = NSTextAlignmentCenter;
subTitleLabel.text = #"28/M";
subTitleLabel.font = customFont1;
subTitleLabel.textAlignment=NSTextAlignmentCenter;
subTitleLabel.numberOfLines = 1;
subTitleLabel.adjustsFontSizeToFitWidth = YES;
subTitleLabel.minimumScaleFactor = 10.0f/12.0f;
subTitleLabel.clipsToBounds = YES;
subTitleLabel.backgroundColor = [UIColor clearColor];
subTitleLabel.textColor = [UIColor blackColor];
patientNameLabel.center = CGPointMake(titleView.frame.size.width/2, 10);
subTitleLabel.center = CGPointMake(titleView.frame.size.width/2, 30);
[titleView addSubview:patientNameLabel];
[titleView addSubview:subTitleLabel];
[self.navigationController.navigationBar addSubview:titleView];
Note : You have set static frame to titleView so if you see your app on different device you will not be able to see the text in exact centre. To avoid this set the titleView frame dynamically based on device/view width.
Try Frame setting like this
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0,20,screenWidth,50)];
UILabel *subTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,25,screenWidth,20)];
UILabel *patientNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,screenWidth,30)];

how to Remove Dynamically Created UIView and UILabel text?

I am adding some dynamic UIView named as *cellSeparator and other UILabels...now what happen is when i again call this code then its rewrite the label text and overwrite on previously created label text...i am not very much aware to this ios development.so can anyone please tell me how can i remove this UIView dynamically before creating again?beacause UIView is dynamically created i dont know how to remove that UIview
UILabel *indexLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, self.view.frame.size.height-150, self.view.frame.size.width/2,30)];
[indexLabel setBackgroundColor:[UIColor clearColor]];
indexLabel.textColor = [UIColor whiteColor];
indexLabel.text = #"Details:-";
indexLabel.font = [UIFont systemFontOfSize:20.00];
UILabel *tagLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, self.view.frame.size.height-120, self.view.frame.size.width/2, 30)];
tagLabel.backgroundColor = [UIColor clearColor];
NSLog(#"LOg %#",imageId);
NSLog(#"LOg %#",imageStyle);
NSLog(#"LOg %#",imageType);
NSLog(#"LOg %#",imageWeight);
tagLabel.text = [NSString stringWithFormat:#"The Id of Jewl Is: %#",imageId];
imageTypelabel= [[UILabel alloc] initWithFrame:CGRectMake(20, self.view.frame.size.height-90, self.view.frame.size.width/2, 30)];
imageTypelabel.backgroundColor = [UIColor clearColor];
imageTypelabel.text = [NSString stringWithFormat:#"The Type of Jewl Is: %#",imageType];
imageStylelabel = [[UILabel alloc] initWithFrame:CGRectMake(20, self.view.frame.size.height-60, self.view.frame.size.width/2, 30)];
imageTypelabel.backgroundColor = [UIColor clearColor];
imageStylelabel.text = [NSString stringWithFormat:#"The style of Jewl Is: %#",imageStyle];
imageWeightlabel = [[UILabel alloc] initWithFrame:CGRectMake(20, self.view.frame.size.height-30, self.view.frame.size.width/2, 30)];
imageStylelabel.backgroundColor = [UIColor clearColor];
imageWeightlabel.text = [NSString stringWithFormat:#"The weight of Jewl Is: %#",imageWeight];
imageWeightlabel.backgroundColor = [UIColor clearColor];
imageWeightlabel.textColor = [UIColor whiteColor];
imageTypelabel.textColor = [UIColor whiteColor];
imageWeightlabel.textColor = [UIColor whiteColor];
tagLabel.textColor = [UIColor whiteColor];
UIImage *imageBegin = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:imageBegin];
UIView *cellSeparator = [[UIView alloc] initWithFrame:CGRectMake(0,545, self.view.frame.size.width ,3)];
cellSeparator.tag=1;
[cellSeparator setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleWidth];
[cellSeparator setContentMode:UIViewContentModeTopLeft];
[cellSeparator setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:cellSeparator];
You could write a method to remove all the subviews of the view and modify this code according to your need.
- (void)removeSubviewsOfView
{
NSArray *subViews = [self.view subviews];
for(UIView *view in subViews)
{
[view removeFromSuperview];
}
}

Resources