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.
Related
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];
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
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.
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.
I'm working on an application, in which I'm required to autoresize the text area on basis of text to be displayed.
Firstly, I'm not sure for this either I should use UILabel (Logically is the best choice for displaying static text, which is in my case) or UITextView.
How I wish to use it?
I want to simply init my Label or text view for that matter with Text.
Instead I define the frame first and then restrict my text in that area.
If you can suggest the right solution, that will be a great help.
I went through documentation and other references but didn't find much which could help me here or I could've overlooked it.
The sizeToFit method worked just great.
I did following.
UILabel *testLabel =[[UILabel alloc] initWithFrame:CGRectMake(6,3, 262,20 )]; // RectMake(xPos,yPos,Max Width I want, is just a container value);
NSString * test=#"this is test this is test inthis is test ininthis is test inthis is test inthis is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...";
testLabel.text = test;
testLabel.numberOfLines = 0; //will wrap text in new line
[testLabel sizeToFit];
[self.view addSubview:testLabel];
You can find a text size with :
CGSize textSize = [[myObject getALongText]
sizeWithFont:[UIFont boldSystemFontOfSize:15]
constrainedToSize:CGSizeMake(maxWidth, 2000)
lineBreakMode:UILineBreakModeWordWrap];
then you can create your UILabel like that :
UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,textSize.width, textSize.height];
[lbl setNumberOfLines:0];
[lbl setLineBreakMode:UILineBreakModeWordWrap];
[lbl setText:[myObject getALongText]];
In Swift:
testLabel = UILabel(frame: CGRectMake(6, 3, 262, 20))
testLabel.text = test
testLabel.numberOfLines = 0
testLabel.sizeToFit()
In Objective C
UILabel *testLabel = [[UILabel alloc] initWithFrame: CGRectMake(6, 3, 262, 20)]];
testLabel.text = test;
testLabel.numberOfLines = 0;
[testLabel sizeToFit];
If you want to resize the UILabel only in height, use this:
#property (nonatomic, weak) IBOutlet UILabel *titleLabel;
CGRect titleLabelBounds = self.titleLabel.bounds;
titleLabelBounds.size.height = CGFLOAT_MAX;
// Change limitedToNumberOfLines to your preferred limit (0 for no limit)
CGRect minimumTextRect = [self.titleLabel textRectForBounds:titleLabelBounds limitedToNumberOfLines:2];
CGFloat titleLabelHeightDelta = minimumTextRect.size.height - self.titleLabel.frame.size.height;
CGRect titleFrame = self.titleLabel.frame;
titleFrame.size.height += titleLabelHeightDelta;
self.titleLabel.frame = titleFrame;
Now you can use titleLabelHeightDelta to layout other views depending on your label size (without using autolayout).
I'm not sure I totally understand the question, but you can use the sizeToFit method on a UILabel (the method is inherited from UIView) to change the size according to the label text.
The easiest way to find the no. of lines depending on text. You can use this code:
ceil(([aText sizeWithFont:aFont].width)/self.bounds.size.width-300);
it returns some float value.
[lbl setNumberOfLines:floatvalue];
Please note that with autolayout call sizeToFit won't change size, because it will be changed later by autolayout calculations. In this case you need to setup proper height constraint for your UILabel with "height >= xx" value.
Because you're going to use this solution countless times in your app, do the following:
1) Create a directory called extensions and add a new file inside called UILabel.swift with the following code:
import UIKit
extension UILabel {
func resizeToText() {
self.numberOfLines = 0
self.sizeToFit()
}
}
2) In your app code, define the label width you want and just call resizeToText():
label.frame.size.width = labelWidth
label.resizeToText()
This will maintain width while increasing the height automatically.
try bellow code, it works for multiline
self.labelText.text = string;
self.labelText.lineBreakMode = NSLineBreakByWordWrapping;
self.labelText.numberOfLines = 0;
You can change the size of label based on length of the string by, using this function
func ChangeSizeOfLabel(text:String) -> CGSize{
let font = UIFont(name: "HelveticaNeue", size: 12)!
let textAttributes = [NSFontAttributeName: font]
let size = text.boundingRectWithSize(CGSizeMake(310, 999), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)
let adjustSize = CGSizeMake(size.width, size.height)
return adjustSize
}
and use it like this :
let
showLabel.frame = CGRectMake(x, y, width , self.ChangeSizeOfLabel("Hello , Height is changing dynamically.....").height)