Fit text in UILabel - objective-c

Here is my code
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 50, 300, 50)];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor whiteColor];
label.textColor.font = [UIFont fontWithName:#"Verdana" size:30];
label.text = #"A very long string";
etc...
The problems is that the font is large and can't fit in the label. It just display "A very"
What to do so entire text to be displayed.
I have tried
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
But it doesn't work for me.
I want to do that programmatically.
//EDIT
CGRect frame = CGRectMake(10, 50, 300, 50);
NSString *labelString = #"Players.";
UILabel *howManyUsersLabel = [[UILabel alloc]initWithFrame:frame];
howManyUsersLabel.textAlignment = UITextAlignmentCenter;
howManyUsersLabel.backgroundColor = [UIColor clearColor];
howManyUsersLabel.textColor = [UIColor whiteColor];
howManyUsersLabel.adjustsFontSizeToFitWidth = NO;
howManyUsersLabel.numberOfLines = 0;
CGFloat fontSize = 30;
while (fontSize > 0.0)
{
CGSize size = [labelString sizeWithFont:[UIFont fontWithName:#"Verdana" size:fontSize] constrainedToSize:CGSizeMake(frame.size.width, 10000) lineBreakMode:UILineBreakModeWordWrap];
if (size.height <= frame.size.height) break;
fontSize -= 1.0;
NSLog(#"test");
}
howManyUsersLabel.font = [UIFont fontWithName:#"Verdana" size:fontSize];

I think you just need to add this:
label.adjustsFontSizeToFitWidth = YES;
label.minimumFontSize = 0;
Then the text will automatically resize to fit the label.
Note however that this will only really work if the label.numberOfLines = 1, so that the text is on a single line.
If you need the text to wrap onto multiple lines but still shrink to fit, the solution is more complex. To do this, you need to calculate the rendered size of the text and then reduce it in a loop, as follows:
NSString *theText = #"A long string";
CGRect labelRect = CGRectMake(10, 50, 300, 50);
label.adjustsFontSizeToFitWidth = NO;
label.numberOfLines = 0;
CGFloat fontSize = 30;
while (fontSize > 0.0)
{
CGSize size = [theText sizeWithFont:[UIFont fontWithName:#"Verdana" size:fontSize] constrainedToSize:CGSizeMake(labelRect.size.width, 10000) lineBreakMode:UILineBreakModeWordWrap];
if (size.height <= labelRect.size.height) break;
fontSize -= 1.0;
}
//set font size
label.font = [UIFont fontWithName:#"Verdana" size:fontSize];
This basically just reduces the font size until it fits the label.
UPDATE:
As of iOS7, multiline text will also shrink automatically when adjustsFontSizeToFitWidth = YES, so the second part of this answer is no longer needed (unless you still support iOS 6 and earlier).

Finally I got solution for text allignment issue in arabic language you just do like this:
label.text = #"هذا هو نص طويل جدا";
label.textAlignment = NSTextAlignmentNatural;
CGSize size = [labels sizeThatFits:CGSizeMake(_lblAddress.width, CGFLOAT_MAX)];
label.height = size.height;

[UILabel sizeToFit];
It will work for your problem.

Swift with iOS 9
let maxFontSize: CGFloat = 40
let minFontSize: CGFloat = 10
label.font = UIFont(name: label.font.fontName, size: maxFontSize)!
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = minFontSize/maxFontSize
This doesn't increase the font size to fill the label. It just starts with the max size and decreases as necessary down to the minimum. This is also assuming that the number of lines is 1.

CGRect titleRect = CGRectMake(10, 50, 300, 50);
UILabel *textTitleView = [[UILabel alloc] initWithFrame:titleRect];
textTitleView.numberOfLines = 3 //for multiple lines;
textTitleView.lineBreakMode = UILineBreakModeWordWrap;
[UIFont fontWithName:#"Verdana" size:30];
textTitleView.text = #"your text";

Interface Builder lets you do this now.
In UILabel, under Autoshrink, select "Minimum Font Size" instead of "Fixed Font Size".
Set the Minimum Font Size to be something reasonable, like 8.
You can also check the checkmark "Tighten Letter Spacing".
Alternatively you can do it programmatically:
label.adjustsFontSizeToFitWidth = YES;

Everything seems to be broken in iOS 8 (probably iOS 7 too).
Solution:
-(UIFont*)fontForString:(NSString*)string toFitInRect:(CGRect)rect seedFont:(UIFont*)seedFont {
UIFont* returnFont = seedFont;
CGSize stringSize = [string sizeWithAttributes:#{NSFontAttributeName : seedFont}];
while(stringSize.width > rect.size.width){
returnFont = [UIFont systemFontOfSize:returnFont.pointSize -1];
stringSize = [string sizeWithAttributes:#{NSFontAttributeName : returnFont}];
}
return returnFont;
}
Make sure you don't try and use label.adjustsFontSizeToFitWidth = YES otherwise it'll get really confused and the new size won't work properly.

Related

Dynamic height for textview in ios?

I have added a UITextView inside a UIView. UIView has some height depending upon screen sizes. UITextView can have more or less text. So I want to make the height of UITextView dynamic so if text is more then it should have more height but it should be less than the height of main view . If text is less then it should have less height.
Size a UITextView to its content programmatically:
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
[textView setDelegate:self];
[textView setText:#"your long text"];
[textView setScrollEnabled:NO];
[self.view addSubview:textView];
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
textView.frame = newFrame;
If you are using textview to display multilines of text with scrolling disabled, It is nothing more than a UILabel. I suggest you to use UILabel for the purpose.
In the storyboard, set the constraints as follows:
and set the line break as word wrap:
Same as the first answer, but in Swift 4:
let screenSize = UIScreen.main.bounds
let textView = UITextView.init(frame: CGRect(x: 1, y: 40, width: screenSize.width, height: screenSize.height))
textView.delegate = self as? UITextViewDelegate
textView.isScrollEnabled = false
view.addSubview(textView)
let fixedWidth = textView.frame.size.width
let newSize: CGSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT)))
var newFrame = textView.frame
newFrame.size = CGSize(width: CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), height: newSize.height)
Try with this
-(void)dynamicTextSize{
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(200, 300, 200, 30)];
textView.center = self.view.center;
[self.view addSubview:textView];
NSString *string = #"This is pour text.a hjajksdkja kajhdsjk akjdhs jakhd skjahs ajkdhsjkad hskja akjdhs ajkhdjskar";
textView.text = string;
//UIFont *font = [UIFont fontWithName:#"Arial" size:16.0f];
NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:textView.font, NSFontAttributeName, nil];
textView.backgroundColor = [UIColor lightGrayColor];
CGRect frame = [textView.text boundingRectWithSize:CGSizeMake(textView.frame.size.width, 10000) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:attrDict context:nil];
CGRect mFrame = textView.frame;
mFrame.size.width = frame.size.width;
mFrame.size.height = frame.size.height;
textView.frame = mFrame;
//NSLog(#"frame2:%#",NSStringFromCGRect(textView.frame));
}

Add padding into UIlabel text?

I've a label in a table cell and I wish to add padding to top,bottom,left and right.
CGRect initialFrame = CGRectMake(10,10,100,20);
UIEdgeInsets contentInsets = UIEdgeInsetsMake(5, 0, 5, 0);
CGRect padd = UIEdgeInsetsInsetRect(initialFrame, contentInsets);
self.rewardLabel = [[UILabel alloc] initWithFrame:padd];
self.rewardLabel.backgroundColor =[UIColor colorWithRed:0.192 green:0.373 blue:0.561 alpha:1];
self.rewardLabel.layer.cornerRadius = 5.0f;
self.rewardLabel.layer.masksToBounds = YES;
self.rewardLabel.textColor = [UIColor whiteColor];
self.rewardLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.rewardLabel.numberOfLines = 1;
self.rewardLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:14];
[self.contentView addSubview:self.rewardLabel];
But it seem like not working. Can anyone tell me how to do?
There are several ways on how to achieve this:
If you do not need a specific background color for your label you could just adjust the labels frame to add the padding (e.g. if your text should start 20px from the cell's left side, set the label's frame's x to 20).
To really add a padding, you could use a custom UILabel subclass and override its drawTextInRect: and intrinsicContentSize methods. (See this question for details)
If you just need a left and right padding you could use an NSAttributedString to add insets to UILabel:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.headIndent = 5.0;
paragraphStyle.firstLineHeadIndent = 5.0;
paragraphStyle.tailIndent = -5.0;
NSDictionary *attrsDictionary = #{NSParagraphStyleAttributeName: paragraphStyle};
label.attributedText = [[NSAttributedString alloc] initWithString:#"Your text" attributes:attrsDictionary];

UILabel how to get label to autosize a name to a maximum width and truncate?

So I've got this UILabel that I'd like to have it auto size to a maximum width, stop, then truncate. The reason for the autosize is that there is another label (date) that I'd like to be just to the right of this by a set amount of pixels (10px).
I've attempted to use a frame on the UILabel but that just statically sets the width,but that didn't work and I need this to auto size...
Screenshot below.
The basic idea is to use size to fit for whenever the label is not too long, then "cut" it off when it's too long. It's pretty much as simple as it sounds.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(32, 96, 90, 16)];
label.backgroundColor = [UIColor greenColor];
label.font = [UIFont fontWithName:#"Helvetica" size:label.frame.size.height];
label.text = #"Johnny Appleseed";
[label sizeToFit];
[self addSubview:label];
const int CUT_OFF_AT_X = 100;
float labelRight = label.frame.origin.x + label.frame.size.width;
if (labelRight > CUT_OFF_AT_X) {
label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, CUT_OFF_AT_X - label.frame.origin.x, label.frame.size.height);
}
labelRight = label.frame.origin.x + label.frame.size.width;
UILabel *badge = [[UILabel alloc] initWithFrame:CGRectMake(labelRight, 96, 90, 16)];
badge.backgroundColor = [UIColor redColor];
badge.font = label.font;
badge.text = #"LEVEL 90";
[badge sizeToFit];
[self addSubview:badge];
Great answer! For swift 3:
if traitCollection.horizontalSizeClass == .compact && ((lbl_FacilityName.text?.length ?? 0) > 15) {
print("if traitCollection.horizontalSizeClass == .compact and label larger than 15 chars ")
//If label is too long cut the width off at the start of the segmented control -3 for padding
lbl_FacilityName.frame = CGRect(x: lbl_FacilityName.frame.origin.x, y: lbl_FacilityName.frame.origin.y, width: ((segPatientSortControl.frame.origin.x - 3) - lbl_FacilityName.frame.origin.x), height: lbl_FacilityName.frame.size.height)
}

Fixing border to UILabel

I am taking text to UILabel which is inside a UItableViewCell(label text is coming from webData-so it varies in size).
I want to give a border for my label, which should fit the text width and height. I have created one, but it's not looking good.
Help me to improve my code.
**Also is there any way to get border with rounded corners ? **
Hey I am getting text inside the border like this, and the corners are not so rounded:
UILabel *cmntBoxlbl = [[UILabel alloc]initWithFrame:CGRectMake(58, 23, 250, 60)];
cmntBoxlbl.font=[UIFont fontWithName:#"Arial" size:12];
cmntBoxlbl.layer.borderColor = [UIColor darkGrayColor].CGColor;
cmntBoxlbl.layer.borderWidth = 1.0;
NSString *text = [NSString stringWithFormat:#"%#%#%#",#" ",[[self.DtlArray objectAtIndex:indexPath.row] objectForKey:#"comment"],#" "];
cmntBoxlbl.text = text;
cmntBoxlbl.textAlignment = UITextAlignmentCenter;
cmntBoxlbl.lineBreakMode = UILineBreakModeWordWrap;
[cmntBoxlbl setTextColor:[UIColor darkGrayColor]];
CGSize expectedLabelSize = [text sizeWithFont:cmntBoxlbl.font
constrainedToSize:cmntBoxlbl.frame.size
lineBreakMode:UILineBreakModeWordWrap];
CGRect newFrame = cmntBoxlbl.frame;
newFrame.size.height = expectedLabelSize.height;
cmntBoxlbl.frame = newFrame;
cmntBoxlbl.numberOfLines = 0;
[cmntBoxlbl sizeToFit];
[cell addSubview:cmntBoxlbl];
*also is there any way to get border with rounded corners ?? *
#import <QuartzCore/QuartzCore.h>
label.layer.borderWidth = 3;
label.layer.borderColor = [[UIColor blackColor] CGColor];
label.layer.cornerRadius = 5;
For rounded corner set.
[cmntBoxlbl.layer setCornerRadius:15];
Also add the QuartzCore framework and import the header:
#import <QuartzCore/QuartzCore.h>

How to calculate the Width and Height of NSString on UILabel

I am working on a project to make the NSString on UILabel Width and Height dynamically.
I tried with:
NSString *text = [messageInfo objectForKey:#"compiled"];
writerNameLabel.numberOfLines = 0;
writerNameLabel.textAlignment = UITextAlignmentRight;
writerNameLabel.backgroundColor = [UIColor clearColor];
CGSize constraint = CGSizeMake(296,9999);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]
constrainedToSize:constraint
lineBreakMode:UILineBreakModeWordWrap];
NSLog(#"sizewidth = %f, sizeheight = %f", size.width, size.height);
NSLog(#"writerNameLabel.frame.size.width 1 -> %f",writerNameLabel.frame.size.width);
[writerNameLabel setFrame:CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, size.width, size.height)];
CGRect labelFram = writerNameLabel.frame;
labelFram.origin.x = cell.frame.size.width - writerNameLabel.frame.size.width - 80;
writerNameLabel.frame = labelFram;
NSLog(#"writerNameLabel.frame.size.width 2-> %f",writerNameLabel.frame.size.width);
Please see the green bubble not the grey one.
Still not right.
The code for bubble
bubbleImageView.frame = CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, writerNameLabel.frame.size.width+15, writerNameLabel.frame.size.height+5);
Please Advise! Thanks!
That's because you did not reuse the table cell, the structure should be like:
NSString *text = [messageInfo objectForKey:#"compiled"];
if(cell == nil)
{
writerNameLabel.numberOfLines = 0;
writerNameLabel.textAlignment = UITextAlignmentRight;
writerNameLabel.backgroundColor = [UIColor clearColor];
[cell addSubview:writerNameLabel];
}
else {
writerNameLabel = (UILabel *)[cell viewWithTag:WRITER_NAME_LABEL_TAG];
}
CGSize constraint = CGSizeMake(296,9999);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]
constrainedToSize:constraint
lineBreakMode:UILineBreakModeWordWrap];
[writerNameLabel setFrame:CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, size.width, size.height)];
I've been gone through and answered some of your question, that's correct way to write your tableview controller. And your problem will be solved.