Get the number of lines in UILabel iOS8 - objective-c

I'm seeing lots of deprecated answers for this question:
How do I calculate the number of lines in use in a UILabel based of its set text?
I know that I need to set the UILabel to have bounds that resize with word wrapping. In this way, I could detect the height of my UILabel and adjust an NSLayoutConstraint for the height of my UITableViewCell. Basically my problem plain and simple is:
How can I determine my UILabel's number of lines in use(based of descriptionLabel.text) or height in order to resize My UITableView's UITableViewCells which contain my UILabel.
Currently I have used this code:
descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 30, 270, 65)];
descriptionLabel.textColor = [UIColor blackColor];
descriptionLabel.numberOfLines = 0;
descriptionLabel.adjustsFontSizeToFitWidth = YES;

Try using the following code
NSAttributedString *attrStr = ... // your attributed string
CGFloat width = 300; // whatever your desired width is
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
//rect is the height of UILABEL which u can used as height of label or table view row or etc

I solved my problem very simply with this code:
CGSize maxSize = CGSizeMake(290.0f, CGFLOAT_MAX);
CGSize requiredSize = [descriptionLabel sizeThatFits:maxSize];
[descriptionLabel setFrame:CGRectMake(15, 50, requiredSize.width, requiredSize.height)];
NSLog(#"THE HEIGHT OF THIS DESCRIPTIONLABEL IS: %f",cell.frame.size.height);

Related

Objective c uilabel width based on text length

I want to set the width of the uilabel based on the text length and then on top of that make it a little bit wider. The text might be different so I cannot just predefine the width of the uilabel. My approach to this is to get the width of the text and then add another 10.0 to it but it doesn't work.
CGSize tSize = [[self.label1 text] sizeWithAttributes:#{NSFontAttributeName:[self.label1 font]}];
CGFloat tWidth = tSize.width + 10.0;
self.label1.frame = CGRectMake(self.label1.frame.origin.x, self.label1.frame.origin.y, tWidth, self.label1.frame.size.height);
self.label1.backgroundColor = [UIColor blueColor];
Any advice is much appreciated.
You might want to use [yourLabel sizeToFit]; or [yourLabel sizeThatFits: <#your target size#>];
sizeToFit resizes your label within it's current frame.size according to it's current text , font and the numberOfLines you provided.
Then you can change the size
[yourLabel sizeToFit];
CGRect rect = yourLabel.frame;
rect.size.width += 10;
yourLabel.frame = rect;
sizeThatFits:(CGSize)size doesn't resize your label but it returns the size that fits the size you pass as parameter.
sizeToFit uses sizeThatFits:(CGSize)size internally.
You can change size by doing this
CGSize exampleSize = (CGSize){300, 300};
CGSize fittingSize = [yourLabel sizeThatFits: exampleSize];
CGRect rect = yourLabel.frame;
rect.size.width = fittingSize.width;
rect.size.height = fittingSize.height;
yourLabel.frame = rect;
This should be working fine even if you are working with yourLabel.attributedText

Drawing line through UITableView cells

Is it possible to draw a line with different width through some cells in UITableView?
Something like this:
I'm using Xcode 4.6 and target is iOS5+
Rough idea on how it might work. You'll need to manage the red line when the reusable cell content changes.
CGSize size = [cell.textLabel.text sizeWithFont:cell.textLabel.font];
CGFloat y = cell.contentView.frame.size.height / 2;
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(5,y,size.width, 3)];
line.backgroundColor = [UIColor redColor];
[cell.textLabel addSubview:line];
make some lines(like image, etc) above the tableViewCell
like [cell.contentView addSubView:$LINE_IMAGE_VIEW]
you can get the label's width like this
CGFloat width = cell.titleLabel.frame.size.width
then assign that width to custom line image.
This will strike through the whole cell. In case you need it to look like completed task:
CGSize size = cell.contentView.frame.size; // you'll draw the line in whole cell.
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(15,size.height / 2,size.width - 30, 1)];
line.backgroundColor = [UIColor grayColor]; // set your preferred color
[cell addSubview:line];
You may indicate some other value in CGRectMake instead of 15 - it's offset by X. In this case you'd better then decrease width by doubled value (in my case it's 15*2 = 30) in order it look nice.

How to change the width of label once after its frame has been set? and to get the width of NSString

hope you are doing good.
I am setting a label and adjusting its frame ..
UILabel *mylabel=[[UILabel alloc]init];
mylabel.Text=#"This is my label";
mylabel.frame=CGRectMake(10,10,200,21);
now if I change the Label's text from any string set by me like this
NSString *mystring=#"This is my first string that is to be assigned to my label dynamilcally";
mylabel.Text=mystring;
mylabel.frame.size.width=mystring.length;
but nothing happens. The width of the label remains 200, as I set while at the time of initialisation.
This will also need to get the width of the mystring . How to get that?
Thank in anticipation for helping me a lot.
[myLabel sizeToFit] if you need it on one line. For multiple line labels you can use NSString's sizeWithFont:constrainedToSize:lineBreakMode: function to get size of your string and use it to modify your label's height & width.
e.g. code that gives you height for multiline label with fixed width of 200px:
CGSize textSize = {
200.0, // limit width
20000.0 // and height of text area
};
CGSize size = [descriptionString sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = size.height < 36? 36: size.height; // lower bound for height
CGRect labelFrame = [myLabel frame];
labelFrame.size.height = height;
[myLabel setFrame:labelFrame];
[myLabel setText:descriptionString];

What's the right way to dynamically give height to a UIScrollView depending on the content within?

Here my dilemma. I have 4 elements inside a UIScrollView.
1. Top most element is a UILabel that I give height dynamically depending upon the amount of content in it.
2. Second is a fixed height UILabel that I give position dynamically depending upon the height given to the upper UILabel
3. Third element is a UIImageView that again I have to give position dynamically depending upon the height given to the topmost UILabel
4. The fourth is a UIWebView, to which I gave both, height & position dynamically. (Height depending upon the content in it.. and position again depending on the height of topmost UILabel)
Finally, I dynamically give height to my UIScrollView to accomodate all of the above elements.
Here is the code I use in - (void)webViewDidFinishLoad:(UIWebView *)webView to accomplish all of the above.
//Adjust height of top-most UILabel
CGSize maximumLabelSize = CGSizeMake(300,9999);
CGSize expectedLabelSize = [item.label1 sizeWithFont:label1.font constrainedToSize:maximumLabelSize lineBreakMode:label1.lineBreakMode];
CGRect newFrame = label1.frame;
newFrame.size.height = 0;
newFrame.size.height = expectedLabelSize.height;
label1.frame = newFrame;
//Adjust position of second UILlabel
CGRect labelPosition = label2.frame;
labelPosition.size.height = 20;
labelPosition.origin.y = expectedLabelSize.height +14;
label2.frame = labelPosition;
//Add UIImageView and adjust it's position
UIImageView *image;
image = [[UIImageView alloc] initWithFrame:CGRectMake(0, expectedLabelSize.height +41, 320, 2)];
image.image = [UIImage imageNamed:#"image.png"];
[scrollView addSubview:image];
[image release];
//Adjust UIWebView height and position
CGRect frame = webView.frame;
frame.size.height = 0;
frame.origin.y = expectedLabelSize.height +48;
webView.frame = frame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
webView.frame = frame;
//Adjust Scrollview height
scrollView.contentSize = CGSizeMake(320, fittingSize.height +expectedLabelSize.height +48);
Finally, my problem is that when I first load this view, everything but the scrollview get's proper height & position. But, if I go back one view & open this view again, the scrollview has the desired height.
Any ideas what I might be doing wrong here?
My guess is that the scrollView variable isn't yet initialized when this first runs. Try setting a breakpoint somewhere in this code and checking if scrollView has a value or if it's just 0x00000000.

How to programmatically add text to a UIView

I have a UIView that I'd like to add several bits of text to. I have used a UITextView but I think that's overkill as it doesn't need to be editable. I thought about using a UILabel or a UITextField, but I don't see how you tell the superview where to position the UILabel or UITextField within itself. I want the lowest footprint object that will let me put text of a font/color/size of my choosing in my UIView where I want it. Not too much to ask, eh?
The simplest approach for you would be:
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 20)];
[yourLabel setTextColor:[UIColor blackColor]];
[yourLabel setBackgroundColor:[UIColor clearColor]];
[yourLabel setFont:[UIFont fontWithName: #"Trebuchet MS" size: 14.0f]];
[yourSuperView addSubview:yourLabel];
Building or populating Views in your code will probably require you to use CGRectMake a lot.
As its name says, it creates a rectangle that you can use to set the relative position (relative to the borders of your superview) and size of your UIView-Subclass (in this case a UILabel).
It works like this:
yourLabel.Frame = CGRectMake(x, y, width, height); //x,y,width,height are float values.
x defines the spacing between the left hand border of the superview and the beginning of the subview your about to add, same applies to y but relating to the spacing between top-border of your superview.
then width and height are self-explanatory i think.
Hope this gets you on the track.
Instead of finding a way to tell the view where to position the UILabel, you can tell the UILabel where to position itself in the view by using "center".
E.g.
myLabel.center = CGPointMake(0.0, 0.0);
Hope you'll be able to use UILabel, for me it's the basic form of a flexible non editable text.
For Swift:
let yourLabel = UILabel(frame: CGRectMake(100, 100, 100, 100))
yourLabel.textColor = UIColor.whiteColor()
yourLabel.backgroundColor = UIColor.blackColor()
yourLabel.text = "mylabel text"
yoursuperview.addSubview(yourLabel)
This question is old, but for a pure UIView text option without using UILabel or UITextField (as all the other answers describe, but the question is how to do it without them), drawRect in a subclassed UIView works for me. Like so:
- (void)drawRect:(CGRect)rect{
NSString *string = #"Hello World!";
[string drawAtPoint:CGPointMake(100, 100) withFont:[UIFont boldSystemFontOfSize:16.0]];
}
This routine displays a text at a X-Y position
-(void)placeText:(NSString *)theText:(int)theX:(int)theY {
UILabel *textLabel;
// Set font and calculate used space
UIFont *textFont = [UIFont fontWithName:#"Helvetica" size:14];
CGSize textStringSize = [theText sizeWithFont:textFont constrainedToSize:CGSizeMake(300,50) lineBreakMode:NSLineBreakByTruncatingTail];
// Position of the text
textLabel = [[UILabel alloc] initWithFrame:CGRectMake(theX+OFFSETIMAGEX-(textStringSize.width/2), theY+OFFSETIMAGEY-(textStringSize.height/2), textStringSize.width,textStringSize.height)];
// Set text attributes
textLabel.textColor = [UIColor blackColor];
textLabel.backgroundColor = [UIColor orangeColor];
textLabel.font = textFont;
textLabel.text = theText;
// Display text
[self.view addSubview:textLabel];
}
It might be late but here is what I use:-
CGRect labelFrame = CGRectMake(120,300, 530, 100);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
//If you need to change the color
[myLabel setTextColor:[UIColor whiteColor]];
//If you need to change the system font
[myLabel setFont:[UIFont fontWithName:NULL size:23]];
//If you need alignment
[myLabel setTextAlignment:NSTextAlignmentCenter];
// The label will use an unlimited number of lines
[myLabel setNumberOfLines:0];
//Add label view to current view
[self.view addSubview:myLabel];
NSString *someString = #"Sample String, Yarp!";
myLabel.text = someString;
add a UILabel to your View. then override the View's layoutSubviews method.