How to add a text label to a tableview in the center? - ios

I use the code below:
label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 44)];
label.center = self.tableView.center;
label.textAlignment = NSTextAlignmentCenter;
label.text=NSLocalizedString(#"Network Not Reachable", nil);
[self.tableView addSubview:label];
But I want the label located in the center of the light gray lines.
You could see the Calendar's screenshot.

Replace your code with below one.
float assumedCellHeight = 44;
float hh = self.tableView.bounds.size.height;
int num = (hh / assumedCellHeight)/2;
num = (num % 2 == 0)?num:num-1;
float yy = assumedCellHeight*num;
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, yy, self.tableView.bounds.size.width, assumedCellHeight)];
// label.center = self.tableView.center;
label.textAlignment = NSTextAlignmentCenter;
label.text=NSLocalizedString(#"Network Not Reachable", nil);
[self.tableView addSubview:label];
It's working for me.
Thanks.

Related

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

Add UILabel to UITextView

I have Multiple UITextView's that I have created with a for-loop programmatically. I'm trying to add a UILabel to the upper left corner of each UITextView also.
How can I do that?
My UITextView code:
for (int i = 0; i < 10; i++){
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, yPos, 375,height)];
[textView setBackgroundColor:[UIColor lightGrayColor]]; //set different property like this
UIColor *borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.0];
textView.layer.borderColor = borderColor.CGColor;
textView.layer.borderWidth = 1.0;
textView.layer.cornerRadius = 5.0;
textView.textAlignment=NSTextAlignmentRight;
textView.editable=NO;
[CommentScrooll addSubview:textView ];
// CommentScroll Is the name of my viewcontroller
yPos += (height + padding);
}
Objective-c code:-
UILabel *cust_Label = [[UILabel alloc] initWithFrame:CGRectMake(Your_X, Your_Y, Your_Width,Your_Height)];
cust_Label.text=#"Your Text";
[textView addSubview: cust_Label];
I've never added a UILabel to a UITextView before but I just tested this and it worked. This is the general idea:
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
label.text = "My Label"
textView.addSubview(label)

UILabel how to autofit content?

I'm working on a personal project which is a simple quote generator.
Users can save favourite their quotes to a list, and in the list view I would like the UILabel to size responsively to the content (some quotes are short, and some are long - which can look a bit odd).
Any help would be greatly appreciated.
UILabel *favouriteLabel;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
favouriteLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, -10, 400, 140)];
}else {
favouriteLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, -20, 180, 130)];
}
favouriteLabel.backgroundColor = [UIColor clearColor];
favouriteLabel.text = [self.arrayFromFile objectAtIndex:indexPath.row];
NSLog(#"Row alloc %d", indexPath.row);
NSLog(#"Load label %#", favouriteLabel.text);
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
favouriteLabel.font = [UIFont fontWithName: #"Eras Bold ITC" size: 18];
}else if([GUIHelper isPhone5]){
favouriteLabel.font = [UIFont fontWithName: #"Dosis-Medium" size: 15];
}
else
favouriteLabel.font = [UIFont fontWithName: #"Dosis-Medium" size: 15];
favouriteLabel.textColor = [UIColor colorWithRed:68.0/255.0 green:68.0/255.0 blue:68.0/255.0 alpha:1];
favouriteLabel.textAlignment = UITextAlignmentCenter;
favouriteLabel.numberOfLines = 0;
favouriteLabel.center = CGPointMake(cell.center.x - 40, cell.center.y + 20);
favouriteLabel.tag = 900;
[cell.contentView addSubview:favouriteLabel];
UIImage *lineImg = [UIImage imageNamed:#"quote-divider#2x.png"];
CGRect lineImageFrame;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
lineImageFrame = CGRectMake(0, 120, lineImg.size.width, lineImg.size.height);
}else{
lineImageFrame = CGRectMake(0, 62, lineImg.size.width * 0.9, 0.8*lineImg.size.height);
}
UIImageView *lineImageView = [[UIImageView alloc] initWithFrame:lineImageFrame];
lineImageView.image = lineImg;
lineImageView.center = CGPointMake(cell.center.x - 40, lineImageView.center.y + 35);
Before you add the label to the view, try [favoriteLabel sizeToFit].

Programmatically Creating UILabel

I know this should be very simple, but I've been really struggling with creating a UILabel programmatically and getting it to behave the way I would like.
All I want is to be able to create a label, set the maximum attributes as far as height, width and font size, and then have the text get smaller AND/OR just truncate the text to accommodate long strings of text.
Let's say that I want my label to have text that has a maximum width of 380, a maximum height of 20 and a maximum font size of 12.
So here is what I have attempted to do to create such a label:
UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, 0, 0)];
fromLabel.text = [self fromSender];
fromLabel.font = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = YES;
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.size = [fromLabel.text sizeWithFont:fromLabel.font constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];
fromLabel.minimumScaleFactor = MIN_SCALE_FACTOR;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];
Ok, so the label appears, but the text is larger than 12 and the height always comes out to be 21!? Even if I change the height and text size values to extreme sizes, this code creates a label of some fixed size that can't be adjusted. The only thing I can seem to make smaller is the width.
I must be over looking something basic, but I really can't figure out how to get my desired result, nor do I understand why I'm getting the behavior that I am getting.
Does the following work ?
UIFont * customFont = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
NSString * text = [self fromSender];
CGSize labelSize = [text sizeWithFont:customFont constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];
UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, labelSize.width, labelSize.height)];
fromLabel.text = text;
fromLabel.font = customFont;
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.minimumScaleFactor = 10.0f/12.0f;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];
edit : I believe you may encounter a problem using both adjustsFontSizeToFitWidth and minimumScaleFactor. The former states that you also needs to set a minimumFontWidth (otherwhise it may shrink to something quite unreadable according to my test), but this is deprecated and replaced by the later.
edit 2 : Nevermind, outdated documentation. adjustsFontSizeToFitWidth needs minimumScaleFactor, just be sure no to pass it 0 as a minimumScaleFactor (integer division, 10/12 return 0).
Small change on the baselineAdjustment value too.
UILabel *lbl1 = [[UILabel alloc] init];
/*important--------- */lbl1.textColor = [UIColor blackColor];
[lbl1 setFrame:position];
lbl1.backgroundColor=[UIColor clearColor];
lbl1.textColor=[UIColor whiteColor];
lbl1.userInteractionEnabled=NO;
lbl1.text= #"TEST";
[self.view addSubview:lbl1];
here is how to create UILabel Programmatically..
1) Write this in .h file of your project.
UILabel *label;
2) Write this in .m file of your project.
label=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];//Set frame of label in your viewcontroller.
[label setBackgroundColor:[UIColor lightGrayColor]];//Set background color of label.
[label setText:#"Label"];//Set text in label.
[label setTextColor:[UIColor blackColor]];//Set text color in label.
[label setTextAlignment:NSTextAlignmentCenter];//Set text alignment in label.
[label setBaselineAdjustment:UIBaselineAdjustmentAlignBaselines];//Set line adjustment.
[label setLineBreakMode:NSLineBreakByCharWrapping];//Set linebreaking mode..
[label setNumberOfLines:1];//Set number of lines in label.
[label.layer setCornerRadius:25.0];//Set corner radius of label to change the shape.
[label.layer setBorderWidth:2.0f];//Set border width of label.
[label setClipsToBounds:YES];//Set its to YES for Corner radius to work.
[label.layer setBorderColor:[UIColor blackColor].CGColor];//Set Border color.
[self.view addSubview:label];//Add it to the view of your choice.
Swift 3:
let label = UILabel(frame: CGRect(x:0,y: 0,width: 250,height: 50))
label.textAlignment = .center
label.textColor = .white
label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.text = "This is a Label"
self.view.addSubview(label)
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = #"Your Text";
[self.view addSubview:label];
In Swift -
var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)
For swift
var label = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 50))
label.textAlignment = .left
label.text = "This is a Label"
self.view.addSubview(label)
UILabel *mycoollabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];
mycoollabel.text=#"I am cool";
// for multiple lines,if text lenght is long use next line
mycoollabel.numberOfLines=0;
[self.View addSubView:mycoollabel];

UILabel number of lines affecting the bounds size

I am having this peculiar behavior with UILabel. Any numberOfLines works ok, except 1. If I set the number of lines to 1 it ignores the width which I set later.
I don't understand why 1 line screws it up...
here is my code
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = #"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.frame = CGRectMake(20, 20, 100, 0);
CGRect rect = label.frame;
label.numberOfLines = 2;
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
rect.size.width = 100;
label.frame = rect;
[label sizeToFit];
Use this code:
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = #"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.frame = CGRectMake(20, 20, 100, 0);
label.numberOfLines = 3;
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
[label sizeToFit];
CGRect rect = label.frame;
rect.size.width = 100;
label.frame = rect;
With numberOfLines = 3:
With numberOfLines = 1:
If you wanna use numberOfLines = 1 in that case your text will be in one line.So please use numberOfLines = 0;
label.numberOfLines = 0;
And there is no need to again define label frame so please remove these statement.
CGRect rect = label.frame;
rect.size.width = 100;
label.frame = rect;
Use this code this is perfect..
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = #"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.frame = CGRectMake(20, 20, 100, 0);
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
[label sizeToFit];
Yes, it doesn't work when numberOfLines=1
I have to add this line at the end to make it work for all cases..
label.width = min(label.width, 100)
Use this as :
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = #"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.numberOfLines = 0;
CGSize labelSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(100 , 9999) lineBreakMode:label.lineBreakMode];
float lHeight = labelSize.height;
label.frame = CGRectMake(20, 20, 100, lHeight);
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
EDIT : - (void)sizeToFit
Description :
Resizes and moves the receiver view so it just encloses its subviews.
Call this method when you want to resize the current view so that it uses the most appropriate amount of space. Specific UIKit views resize themselves according to their own internal needs. In some cases, if a view does not have a superview, it may size itself to the screen bounds. Thus, if you want a given view to size itself to its parent view, you should add it to the parent view before calling this method.
// [label sizeToFit];
Hope it helps you.

Resources