UIlabel's text truncation - ios

I have a UITableView. In that, each cell contains a UILabel. But, text in UILabel is not truncating if it exceeds UIlabel's frames width.
I have tried following options, but nothing is working.
1> set the LineBreakMode as NSLineBreakByTruncatingTail and setNumberOfLines:1
2> set the LineBreakMode as NSLineBreakByWordWrapping and `setNumberOfLines:1
In storyboard also, same settings are present.
Here is the code snippet:
NSString * fullName;
// FullName assignment code
UILabel *label = (UILabel *)[cell.contentView viewWithTag:100];
NSLog(#"textlabel width: %f , text size : %d ", label.bounds.size.width,fullName.length);
label.adjustsFontSizeToFitWidth = NO;
label.text = fullName;
[label setLineBreakMode:NSLineBreakByTruncatingTail];
[label setNumberOfLines:1];
[label sizeToFit];
[label setTextColor:[UIColor whiteColor]];

It's because you do sizeToFit which adjusts the UILabelss width accordingly to its content.
And by the way: Do you have a reason for using tags and not IBOutlet? I think you've set up the UILabelin Storyboard?

Try setting this,
[label setAutoresizingMask:UIViewAutoresizingNone];

Related

Getting the actual height of a UITextView

I have a NSAttributedString being passed into a UITextView:
NSAttributedString *str = #"A really long string ... that continues for awhile";
The string is random in length and I want to pass it into a UITextView.
myTextView.attributedText = str;
I need the width of the UITextView to be 300 but how do I find the heigt?
If I'm not mistaken you can do this:
[myTextView sizeToFit];
And then retrieve the height from myTextView.bounds.size.height. Note though that UITextViews also add some padding to the edges so you may want to subtract that from the height.
If I am mistaken than here is an alternative that is less clean but will work:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300.f, yourMaxHeight)];
label.attributedText = myTextView.attributedText;
label.numberOfLines = INFINITY;
[label sizeToFit];
CGFloat height = label.bounds.size.height;
This of course does not include the UITextView padding.

Width of UILabel created programmatically

I'm trying to create a UILabel programmatically that fits it's content.
The best I could do was to use the NSString's method sizeWithAtributes to get it's content's required width and then apply a constraint that fixes the width to that value.
Is this the way it is supposed to be done using autolayout?
if you need some with aoutolayouts, i try comment:
UILabel *testLabel = [UILabel new];
[testLabel setFont:[UIFont systemFontOfSize:16]];
[testLabel setText:#"Test text for size context"];
[testLabel setTextAlignment:NSTextAlignmentLeft];
[testLabel setNumberOfLines:0]; //0 - infiniy lines if not enough space more
[testLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal]; // Autolayout rule: The higher the priority, the more important hold the text.. by horizontal
[testLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];//some like above but verticale
[testLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];// reverse like Hugging but Compression. then lower priority then text croping.
[testLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisVertical];
[testLabel preferredMaxLayoutWidth:200];//Start new line each 200 points width
[testLabel setPreferredMaxLayoutWidth:YES];// resize Font size by label size.
[testLabel setTranslatesAutoresizingMaskIntoConstraints:NO]; // Disable autolaresize, enable autolayouts
At First read the best answer for any question about UILabel
And also by using following code you can create dynamic size of UILabel
UILabel *myLabelName = [[UILabel alloc] init];
myLabelName.backgroundColor = [UIColor redColor];
[myLabelName setFont: [UIFont fontWithName:#"OpenSans" size:13]]; // set font and it's size as per your requirement.
myLabelName.textAlignment = NSTextAlignmentLeft;
myLabelName.frame = CGRectMake(lblComplainTitle.frame.origin.x + lblComplainTitle.frame.size.width + 7, lblComplainTitle.frame.origin.y +2, 160, 20);
myLabelName.text = #"This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text.";
myLabelName.textColor = [UIColor blackColor];
[self setDynamicHeightOfLabel:myLabelName withLblWidth:160 andFontSize:13]; // here in this function you need to pass object of label with width (as you wabt) and font size
[self.view addSubview:myLabelName];
Code of function, name is setDynamicHeightOfLabel:withLblWidth:andFontSize
-(void) setDynamicHeightOfLabel:(UILabel *) myLabel withLblWidth:(CGFloat) width andFontSize:(int) fontSize
{
CGSize myLabelSize = CGSizeMake(width, FLT_MAX);
CGSize expecteingmyLabelSize = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:myLabelSize lineBreakMode:myLabel.lineBreakMode];
CGRect lblFrame = myLabel.frame;
lblFrame.size.height = expecteingmyLabelSize.height;
myLabel.frame = lblFrame;
int addressLine = myLabel.frame.size.height/fontSize;
myLabel.numberOfLines = addressLine;
}
I create function because you can create any label with dynamic size without use of repeated code.
There is a couple of steps that you have to do to achieve this using autolayout.
Set layout constrains for the label.
Set height constraint with low priority.
Set numberOfLines to 0 to allow multiline text.
Set preferredMaxLayoutWidth for the label.
The preferredMaxLayoutWidth is used by label to calculate its height.
This property affects the size of the label when layout constraints
are applied to it. During layout, if the text extends beyond the width
specified by this property, the additional text is flowed to one or
more new lines, thereby increasing the height of the label.
Hi you can manage the width of lable by doing so programatically,
CGRect frame;
frame =self.yourLabel.frame;
frame.size.width +=20;
self.yourLabel.frame=frame;
Thanks

How add Multiple Lines in Same UILabel

Any way to have multiple lines of text in UILabel ?
I dont wish to more than 1 label in the view.
How to add multiple lines in a single UILabel??
Yes there is a way. Just you need to add two property of UILabel i.e.
NumberOfLines=0 It'll allow you to add multiple lines in a UILabel
LineBreakMode = NSLineBreakByWordWrapping It'll allow you to break your sentence by word. You can also change it according to your requirement.
[YourLabel setNumberOfLines:0];
[YourLabel setLineBreakMode:NSLineBreakByWordWrapping];
You can also set this two property form your interface builder
here is a sample code
UILabel *pHolder1 = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 245, 45)];
pHolder1.backgroundColor = [UIColor clearColor];
pHolder1.font = [UIFont systemFontOfSize:14.0f];
pHolder1.numberOfLines =0;
pHolder1.lineBreakMode = NSLineBreakByWordWrapping;
pHolder1.textAlignment = NSTextAlignmentCenter;
Dynamically calculate the height of UILabel
please refer the below post
Adjust UILabel height depending on the text
Here is sample code:
UILabel *lblUsername=[[UILabel alloc] init];
StoryTextSize = [storytext sizeWithFont:[UIFont fontWithName:#"Georgia" size:13.0f] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
lblUsername.frame=CGRectMake(20, 5, [[UIScreen mainScreen] bounds].size.width-40, StoryTextSize.height);
lblUsername.textColor=[UIColor blackColor];
lblUsername.text=[NSString stringWithFormat:#"%#",[[tblRecords objectAtIndex:indexPath.row] valueForKey:#"username"]];
lblStoryText.numberOfLines=nooflines;
lblStoryText.backgroundColor=[UIColor clearColor];
[self.view addSubview:lblStoryText];
make sure that your label height should be more so total no of lines become visible.

Positioning UILabel inside a UITextView

Trying to position a UILabel above some text, but the elements are "stepping" on each other. I positioned them with x,y,h,w such that they should not do this but alas, they are. You can see in the screenshot that the label text "Abalone" and the text are commingled. What changes do I need to make here? I've already tried changing the x,y,w,h values to no great effect...
txtView = [[UITextView alloc] initWithFrame:CGRectMake(10,20,280,300)];
[txtView setFont:[UIFont fontWithName:#"ArialMT" size:14]];
txtView.text = word.definition;
txtView.editable = NO;
txtView.scrollEnabled = YES;
[txtView scrollRangeToVisible:NSMakeRange([txtView.text length], 0)];
txtView.minimumZoomScale = 1;
txtView.maximumZoomScale = 10;
UILabel *wordTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 250, 20)];
wordTitle.text = word.term;
[txtView addSubview:wordTitle];
[detailsViewController.view addSubview:txtView];
I think the problem is you are adding the label view as a subview to UITextview. You have to reserve some space for the label view in the UITextview. You can either add some padding to the textView, which can be confusing, because padding in UITextView is not constant and varies based on the font size. Or you can add your UILabel directly to the detailsViewController.view and start your UITextView below the label.
Hope it helps.

Get the numberOfLines from a UILabel after resizing it

I do this to make my UIlabel, setting the numberOfLines to 0 so that it has no line-limit:
UILabel *nmLbl = [[UILabel alloc] initWithFrame:CGRectZero];
[nmLbl setFont:[UIFont boldSystemFontOfSize:16.0f]];
[nmLbl setNumberOfLines:0];
[self addSubview:nmLbl];
[nmLbl release];
Later on, when I know which string goes into the label, I size it like this:
nameSize = [[self name] sizeWithFont:[UIFont boldSystemFontOfSize:16.0f] constrainedToSize:maxNameSize lineBreakMode:UILineBreakModeWordWrap];
[self.nameLabel setFrame:CGRectMake(0.0f, 0.0f, nameSize.width, nameSize.height)];
[self.nameLabel sizeToFit];
Now, for my particular use, I need to know how many lines this ends up taking.
If I access the numberOfLines property of the UILabel it will always return 0.
Is there a way for me to directly access how many lines the UILabel ended up being without
having to calculate it, again, by going label.size.height / fontHeight?
Thank you in advance.
No. numberOfLines is a configuration setting, not a reflection of the current formatting.

Resources