Make background UILabel bigger - ios

I have a question in my app I have a number label (IBOutlet). And when I write self.numberLabel.backgroundColor = [UIColor redColor]; is showing a red color fit in the height of number, All I want is to make the background a little bit bigger. Thanks

self.numberLabel.frame = CGRectMake(self.numberLabel.frame.origin.x, self.numberLabel.frame.origin.y, widht, newHeight);
and to make sure font stay same size if needed
[self.numberLabel setFont:[UIFont systemFontOfSize:35]];

You have to set constraints in Interface Builder / Storyboard to fix your label height/width.
If your label's content changes in width, you can use this to calculate a new width with a bit of space left:
float labelWidth =
[self.myLabel.text
boundingRectWithSize:self.myLabel.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{ NSFontAttributeName:self.myLabel.font }
context:nil]
.size.width;
CGRect rect = self.myLabel.bounds;
rect.size.width = labelWidth + 15.0f; //replace 15.0F with the value you want
[self.myLabel setBounds:rect];

There're many ways to skin a cat... in my case the content of the "uilabel" determines its size. I just want the background to be slightly bigger -- 5 points vertically, 7 points horizontally. So I use autolayout to solve it.
Add a uilabel as a subview to the background which is a uiview
Add constraints in IB between the uilabel and the uiview
Add constraints in IB between the uiview and its superview

Related

How can I trim the height of UILabel to perfectly fit the text without ever changing font size?

Here is my UILabel (defined by what is in the yellow):
Here is after I add [shortDescriptionLabel sizeToFit]; to end of my code:
Here is a second example (to show that the font size is actually getting changed after sizeToFit:
Here is after I add [shortDescriptionLabel sizeToFit]; to end of my code (it is clear that the font size reverted back to size 30.0):
I would like to trim the excess height (above and below carrots). How can I do this? Here is my current code:
shortDescriptionLabel = [[UILabel alloc]initWithFrame:CGRectMake(itemImageView.frame.origin.x+itemImageView.frame.size.width+10, 20, self.tableView.frame.size.width-itemImageView.frame.origin.x- itemImageView.frame.size.width-20-20, tableViewCellHeight/2)];
shortDescriptionLabel.text = itemObject.shortDescription;
shortDescriptionLabel.font = [UIFont boldSystemFontOfSize:30];
shortDescriptionLabel.textAlignment = NSTextAlignmentCenter;
shortDescriptionLabel.adjustsFontSizeToFitWidth = YES;
shortDescriptionLabel.numberOfLines = 0;
shortDescriptionLabel.minimumScaleFactor = 0;
[shortDescriptionLabel setBackgroundColor:[UIColor yellowColor]];
CGFloat fontSize = shortDescriptionLabel.font.pointSize;
NSLog(#"fontSize = %f", fontSize);
Keep in mind that the last NSLog will always display 30.0 (the font size set earlier) even if the displayed font size is obviously smaller than 30.0.
Please help. There seems to be a lot about this online but I can't seem to get anything to work.
Yoh can use sizeToFit but if you want to trim the height and keep the width you can add a height constraint equal to the used UIFont's lineHeight.
AutoLayout
1-Properly Add its Leading,Trailing,Top and bottom Constraints and Write this line of code will do
[label setPreferredMaxLayoutWidth:300.0];
Non AutoLayout
-(CGSize)m_GetHeight:(NSString*)text
{
CGSize constraintSize=[text sizeWithFont:[UIFont fontWithName:#"Arial" size:15.] constrainedToSize:CGSizeMake(182, 2000) lineBreakMode:NSLineBreakByWordWrapping];
return constraintSize;
}

iOs 8 seems to be ignoring my UILabel's X and Y coordinates

I have a somewhat old Objective C function that adds a UILabel to my UIView. It keeps track of the last label's Y in the variable _nextFieldY so it can put the next label below it. When I'm adding the label, I init it with its Width, Height, X and Y, and add it to my view. In iOs 7, this works, and correctly puts everything in its place. However, with any devices running the same app in iOs 8+, it appears the labels are all put at (0,0); the labels are all on top of each other in the top left corner. Was there a change between these versions that would cause this? I usually avoid programmatically adding things to my XIBs, so I don't know if there's certain work I have to do to get them to behave.
CGFloat labelWidth = 100;
CGFloat labelHeight = 40;
CGFloat labelY = _nextFieldY-REG_FORM_PADDING_Y;
UIFont *labelFont = [UIFont boldSystemFontOfSize:12.0f];
UILabel *currLabel = [[UILabel alloc] initWithFrame:CGRectMake(REG_FORM_OFFSET_X, labelY, labelWidth, labelHeight)];
currLabel.text = label;
[currLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[currLabel setFont:labelFont];
[currLabel setTextAlignment:NSTextAlignmentLeft];
[_formView addSubview:currLabel];
_nextFieldY += currLabel.frame.size.height + REG_FORM_PADDING_Y;
Since you're setting the frame directly to position your view, you should be leaving translatesAutoresizingMaskIntoConstraints set to YES. Setting it to NO tells the system that it can ignore the frame you set.

Stretch width of UILabel according to width of containing text with background image

I have the following problem - I need to create two UI labels along side one another as in the screen shot below -
The UI label containing the special offers text is dynamic and needs to adjust to the width of the containing text and also if possible display the slanted orange background with the relevant padding -
I'm predominantly a Front-end dev - so with CSS i'd use a long background image that aligns to the right of the label and pad accordingly - but I have no idea how to approach this in objective C - can anyone offer any advice?
This is not a drop-in solution, but perhaps helps you find it (assuming you don't use Auto Layout):
You need a UIImageView for the background and a UILabel for the text
Use a tileable/strechable image (probably with cap insets) for the background (see [UIImage resizableImageWithCapInsets:resizingMode:])
Set the text on your label
Call [label sizeToFit] to resize the label to exactly fit the contained text
Resize the image view depending on the label's size (e.g. imageView.frame = CGRectInset(label.frame, -10, -10), which would make your image view 10pt larger than the label on all sides).
With Auto Layout you'd just define the appropriate constraints between the label and the image view and rely on the label's "intrinsic content size" - should be quite easy.
You could always shrink the text when it gets to long for the label, go into your view controller, click on the label that you would like to shrink when the text gets too long, then, go down to Autoshrink under Label in the attributes inspector. Change it from fixed font size to minimum font size, then I recommend putting 6 to 8 as the lowest font size. This is going to be the LOWEST font size though, so if XCode can make the label fit while making the font size 9, yet the lowest is 7, it will do it.
Or, you could get the length of the string with
int *stringLength = [myString length]
which counts spaces too, then, change the orange square with
orangeBoxImageView.frame = CGRectMake(0, 0, resizedWidth, resizedHeight);
so you could do something like this with your code:
if(stringLength == 15{
orangeBoxImageView.frame = CGRectMake(0, 0, 15, 5);
}
I hope this could help you
CGFloat rect = [YOURSTRING
boundingRectWithSize: (CGSize){ labelWidth, CGFLOAT_MAX }
options: NSStringDrawingUsesLineFragmentOrigin
attributes: #{ NSFontAttributeName : labelFont };
context: nil];
This assumes numberOfLines = 0.
What you want to use is UILabel -sizeToFit inherited from UIView. You should be able to figure out the rest from there.
Find the size of the containing text with
[text sizeWithFont:font constrainedToSize:CGSizeMake(width, height) lineBreakMode:NSLineBreakModexx]
Once you have that, you can manipulate the size of the label accordingly.
Hope this helps
For the background I'd create a subclass of UILabel that overrides drawInRect:, such as this example that simply draws a rectangle with the size of the label
-(void) drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(c, [UIColor redColor].CGColor);
CGContextFillRect(context, rect);
}
Rather than drawing a rectangle, you should create a path with the shape that you need and fill that. See here for more info:
http://weblog.invasivecode.com/core-graphics
I don't know how you've created your label, but if it's done properly with autolayout it'll have the correct width automagically. See here:
http://www.raywenderlich.com/20881/
Tim

Dynamically change UILabel width not work with autolayout

I have some code:
CGRect currentFrame = textLabel.frame;
CGSize max = CGSizeMake(textLabel.frame.size.width, 3000);
CGSize expected = [[textLabel text] sizeWithFont:textLabel.font constrainedToSize:max lineBreakMode:textLabel.lineBreakMode];
currentFrame.size.height = expected.height;
textLabel.frame = currentFrame;
expected.height = expected.height + 70;
[scrollView setContentSize:expected];
textLabel placed inside UIScrollView to display multiline text information.
In older version of application, without 4-inch screen support, everything was perfect.
But now, unfortunately, resizing UILabel does not work.
Maybe, somebody can advice me, what should I change?
Thanks.
When using AutoLayout you should not update the frame property, instead modify the contraints on a view.
On the other hand, you could also let AutoLayout work for you. Make sure the numberOfLines property of the label is set to 0 and the height constraint is of type Greater Than or Equal (>=). This way the layout will update automatically after setting new text on a label.

UILabel - auto-size label to fit text?

Is it possible to auto-resize the UILabel box/bounds to fit the contained text?
(I don't care if it ends up larger than the display)
So if a user enters "hello" or "my name is really long i want it to fit in this box", it is never truncated and the label is 'widened' accordingly?
Please check out my gist where I have made a category for UILabel for something very similar, my category lets a UILabel stretch it's height to show all the content: https://gist.github.com/1005520
Or check out this post: https://stackoverflow.com/a/7242981/662605
This would stretch the height, but you can change it around easily to work the other way and stretch the width with something like this, which is I believe what you want to do:
#implementation UILabel (dynamicSizeMeWidth)
- (void)resizeToStretch{
float width = [self expectedWidth];
CGRect newFrame = [self frame];
newFrame.size.width = width;
[self setFrame:newFrame];
}
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize maximumLabelSize = CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX);
CGSize expectedLabelSize = [[self text] sizeWithFont:[self font]
constrainedToSize:maximumLabelSize
lineBreakMode:[self lineBreakMode]];
return expectedLabelSize.width;
}
#end
You could more simply use the sizeToFit method available from the UIView class, but set the number of lines to 1 to be safe.
iOS 6 update
If you are using AutoLayout, then you have a built in solution. By setting the number of lines to 0, the framework will resize your label appropriately (adding more height) to fit your text.
iOS 8 update
sizeWithFont: is deprecated so use sizeWithAttributes: instead:
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize expectedLabelSize = [[self text] sizeWithAttributes:#{NSFontAttributeName:self.font}];
return expectedLabelSize.width;
}
Using [label sizeToFit]; will achieve the same result from Daniels Category.
Although I recommend to use autolayout and let the label resize itself based on constraints.
If we want that UILabel should shrink and expand based on text size then storyboard with autolayout is best option. Below are the steps to achieve this
Steps
Put UILabel in view controller and place it wherever you want. Also put 0 for numberOfLines property of UILabel.
Give it Top, Leading and Trailing space pin constraint.
Now it will give warning, Click on the yellow arrow.
Click on Update Frame and click on Fix Misplacement. Now this UILabel will shrink if text is less and expand if text is more.
This is not as complicated as some of the other answers make it.
Pin the left and top edges
Just use auto layout to add constraints to pin the left and top sides of the label.
After that it will automatically resize.
Notes
Don't add constraints for the width and height. Labels have an intrinsic size based on their text content.
Thanks to this answer for help with this.
No need to set sizeToFit when using auto layout. My complete code for the example project is here:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var myLabel: UILabel!
#IBAction func changeTextButtonTapped(sender: UIButton) {
myLabel.text = "my name is really long i want it to fit in this box"
}
}
If you want your label to line wrap then set the number of lines to 0 in IB and add myLabel.preferredMaxLayoutWidth = 150 // or whatever in code. (I also pinned my button to the bottom of the label so that it would move down when the label height increased.)
If you are looking for dynamically sizing labels inside a UITableViewCell then see this answer.
Use [label sizeToFit]; to adjust the text in UILabel
Here's what I am finding works for my situation:
1) The height of the UILabel has a >= 0 constraint using autolayout. The width is fixed.
2) Assign the text into the UILabel, which already has a superview at that point (not sure how vital that is).
3) Then, do:
label.sizeToFit()
label.layoutIfNeeded()
The height of the label is now set appropriately.
I created some methods based Daniel's reply above.
-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
CGSize maximumLabelSize = CGSizeMake(290, FLT_MAX);
CGSize expectedLabelSize = [text sizeWithFont:label.font
constrainedToSize:maximumLabelSize
lineBreakMode:label.lineBreakMode];
return expectedLabelSize.height;
}
-(void)resizeHeightToFitForLabel:(UILabel *)label
{
CGRect newFrame = label.frame;
newFrame.size.height = [self heightForLabel:label withText:label.text];
label.frame = newFrame;
}
-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
label.text = text;
[self resizeHeightToFitForLabel:label];
}
#implementation UILabel (UILabel_Auto)
- (void)adjustHeight {
if (self.text == nil) {
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, 0);
return;
}
CGSize aSize = self.bounds.size;
CGSize tmpSize = CGRectInfinite.size;
tmpSize.width = aSize.width;
tmpSize = [self.text sizeWithFont:self.font constrainedToSize:tmpSize];
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, aSize.width, tmpSize.height);
}
#end
This is category method. You must set text first, than call this method to adjust UILabel's height.
You can size your label according to text and other related controls using two ways-
For iOS 7.0 and above
CGSize labelTextSize = [labelText boundingRectWithSize:CGSizeMake(labelsWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{
NSFontAttributeName : labelFont
}
context:nil].size;
before iOS 7.0 this could be used to calculate label size
CGSize labelTextSize = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
// reframe other controls based on labelTextHeight
CGFloat labelTextHeight = labelTextSize.height;
If you do not want to calculate the size of the label's text than you can use -sizeToFit on the instance of UILabel as-
[label setNumberOfLines:0]; // for multiline label
[label setText:#"label text to set"];
[label sizeToFit];// call this to fit size of the label according to text
// after this you can get the label frame to reframe other related controls
Add missing constraints in storyboard.
Select UILabel in storyboard and set the attributes "Line" to 0.
Ref Outlet the UILabel to Controller.h with id:label
Controller.m and add [label sizeToFit]; in viewDidLoad
the sizeToFit() method doesn't play well with constraints, but as of iOS 9 this is all you need -
label.widthAnchor.constraint(equalToConstant: label.intrinsicContentSize.width).activate()
I had a huge problems with auto layout.
We have two containers inside table cell. Second container is resized depending on Item description (0 - 1000 chars), and row should be resized based on them.
The missing ingredient was bottom constraint for description.
I've changed bottom constraint of dynamic element from = 0 to >= 0.
Fits everytime! :)
name.text = #"Hi this the text I want to fit to"
UIFont * font = 14.0f;
CGSize size = [name.text sizeWithAttributes:#{NSFontAttributeName: font}];
nameOfAssessment.frame = CGRectMake(400, 0, size.width, 44);
nameOfAssessment.font = [UIFont systemFontOfSize:font];
you can show one line output then set property Line=0 and show multiple line output then set property Line=1 and more
[self.yourLableName sizeToFit];
There's also this approach:
[self.myLabel changeTextWithAutoHeight:self.myStringToAssignToLabel width:180.0f];

Resources