Add left/right horizontal padding to UILabel - ios

I need to create a UILabel with a background color, and I'd like to add some left/right leading/trailing horizontal padding.
But every solution I've found seems like a nasty hack.
What is the 'standard' way to achieve this from iOS 5 forward?
A screenshot to illustrate my scenario:

For a full list of available solutions, see this answer: UILabel text margin
Try subclassing UILabel, like #Tommy Herbert suggests in the answer to [this question][1]. Copied and pasted for your convenience:
I solved this by subclassing UILabel and overriding drawTextInRect: like this:
- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = {0, 5, 0, 5};
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

The most important part is that you must override both intrinsicContentSize() and drawTextInRect() in order to account for AutoLayout:
var contentInset: UIEdgeInsets = .zero {
didSet {
setNeedsDisplay()
}
}
override public var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + contentInset.left + contentInset.right, height: size.height + contentInset.top + contentInset.bottom)
}
override public func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, contentInset))
}

add a space character too the string. that's poor man's padding :)
OR
I would go with a custom background view but if you don't want that, the space is the only other easy options I see...
OR write a custom label. render the text via coretext

#define PADDING 5
#interface MyLabel : UILabel
#end
#implementation MyLabel
- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = UIEdgeInsetsMake(0, PADDING, 0, PADDING);
CGRect rect = UIEdgeInsetsInsetRect(rect, insets);
return [super drawTextInRect:rect];
}
- (CGRect)textRectForBounds:(CGRect)bounds
limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGSize size = CGSizeMake(999, 999);
CGRect rect = [self.attributedText
boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return CGRectInset(rect, -PADDING, 0);
}
#end

UIView* bg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 70)];
bg.backgroundColor = [UIColor blackColor];
UILabel* yourLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, y, yourWidth, yourHeight)];
[bg addSubview:yourLabel];
[self addSubview:bg];

Sometimes it's convenient to use UNICODE partial spaces to achieve alignment while prototyping. This can be handy in prototyping, proof-of-concept, or just to defer implementation of graphics algorithms.
If you use UNICODE spaces for convenience, be aware that at least one of the UNICODE spaces has a size based on the font it is displayed from, specifically the actual space character itself (U+0020, ASCII 32)
If you're using the default iOS system font in a UILabel, the default System font characteristics could change in a subsequent iOS release and suddenly introduce an unwanted misalignment by changing your app's precise spacing. This can and does happen, for example the "San Francisco" font replaced a previous iOS system font in an iOS release.
UNICODE easy to specify in Swift, for example:
let six_per_em_space = "\u{2006}"
Alternatively, cut/paste the space from an HTML page directly into the UILabel's text field in Interface Builder.
Note: Attached pic is a screenshot, not HTML, so visit the linked page if you want to cut/paste the space.

I had a couple of issues with the answers here, such as when you added in the padding, the width of the content was overflowing the box and that I wanted some corner radius. I solved this using the following subclass of UILabel:
#import "MyLabel.h"
#define PADDING 8.0
#define CORNER_RADIUS 4.0
#implementation MyLabel
- (void)drawRect:(CGRect)rect {
self.layer.masksToBounds = YES;
self.layer.cornerRadius = CORNER_RADIUS;
UIEdgeInsets insets = {0, PADDING, 0, PADDING};
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
- (CGSize) intrinsicContentSize {
CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ;
intrinsicSuperViewContentSize.width += PADDING * 2 ;
return intrinsicSuperViewContentSize ;
}
#end
Hope that's helpful to someone! Note that if you wanted padding on the top and bottom, you would need to change this lines:
UIEdgeInsets insets = {0, PADDING, 0, PADDING};
To this:
UIEdgeInsets insets = {PADDING, PADDING, PADDING, PADDING};
And add this line underneath the similar one for width:
intrinsicSuperViewContentSize.height += PADDING * 2 ;

Swift 5
Create below class file and set it to your label as custom class name through storyboard. That's it.
class PaddingLabel: UILabel {
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)//CGRect.inset(by:)
super.drawText(in: rect.inset(by: insets))
}
}

If you want to add padding to UILabel but not want to subclass it you can put your label in a UIView and give paddings with autolayout like:
Result:

One thing I did to overcome this issue was to use a UIButton instead of a UILabel. Then in the Attributes Inspector of the Interface Builder, I used the Edge for the Title as the padding.
If you do not attach the button to an action, when clicked it will not get selected but it will still show the highlight.
You can also do this programmatically with the following code:
UIButton *mButton = [[UIButton alloc] init];
[mButton setTitleEdgeInsets:UIEdgeInsetsMake(top, left, bottom, right)];
[mButton setTitle:#"Title" forState:UIControlStateNormal];
[self.view addSubView:mButton];
This approach gives the same result but sometimes it did not work for some reason that I did not investigate since if possible I use the Interface Builder.
This is still a workaround but it works quite nicely if the highlight doesn't bother you. Hope it is useful

Subclass UILabel and override drawTextInRect: like this:
- (void)drawTextInRect:(CGRect)rect
{
UIEdgeInsets insets = {0, 10, 0, 0};
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

Installation with CocoaPods
pod 'PaddingLabel', '1.2'
Change your UILabel class to PaddingLabel ###
Specify padding

If you need a more specific text alignment than what adding spaces to the left of the text provides, you can always add a second blank label of exactly how much of an indent you need.
I've got buttons with text aligned left with an indent of 10px and needed a label below to look in line.
It gave the label with text and left alignment and put it at x=10 and then made a small second label of the same background color with a width = 10, and lined it up next to the real label.
Minimal code and looks good.
Just makes AutoLayout a little more of a hassle to get everything working.

Related

How can I enforce an UILabel to be wider than it should be, by 5 points?

I have an UILabel, it has background color as green. But It wraps the text very closely. I need the green background to be little wider than the text, approx 5 points. How can I achieve this?
Details
Label is created in storyboard and has horizontal spacing constraints. You can ignore the constraints as I guess, because I have handled it for any width.
Suggested Requirement
I guess I need a method which I can override in my UILabel's subclass, to increase its width by 5 points. Anybody knows which method I shoul override?
You may try to subclassing of UILabel class and overriding below method -
- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = {0, 5, 0, 5};
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
Hope this will be help you !
You can achieve it by calling sizeToFit first, it will shrink the frame and fit to text, then you can increase width by 10 pixels and remember to keep it center aligned.
Hope it helps.. Let me know... :)
Finally I solved my problem! It works great like this -
Make a subclass of UILabel and override the intrinsicContentSize and sizeThatFits to achieve what you want.
So, something like:
- (CGSize) intrinsicContentSize
{
return [self addHorizontalPadding:[super intrinsicContentSize]];
}
- (CGSize)sizeThatFits:(CGSize)size
{
return [self addHorizontalPadding:[super intrinsicContentSize]];
}
- (CGSize)addHorizontalPadding:(CGSize)size
{
if (size.width > 0)
return CGSizeMake(size.width + (2*kSomeHorizontalPaddingValue), size.height);
else
return size;
}
Note that this only touches the horizontal padding, but can obviously be modified to add vertical padding as well.
I think below code will be working for you
CGFloat width = [label.text sizeWithFont:[UIFont systemFontOfSize:22 ]].width;
label.frame = CGRectMake(point.x, point.y, width+5,height);

Make background UILabel bigger

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

ios7 uitableviewcell image left offset

In iOS 6 and earlier a uitableviewcell's imageView was positioned all the way over to the left with a 0 offset. In iOS 7 though this has been changed and there is now a 15 point space now. I would like to position the imageView like it is in iOS 6. I'm already subclassing the uitableviewcell with AKHighlightableAttributedCell to deal with attributed text not being highlighted. So based on some searching I added:
- (void) layoutSubviews
{
[super layoutSubviews];
// Makes imageView get placed in the corner
self.imageView.frame = CGRectMake( 0, 0, 80, 80 );
}
The issue is everything else still doesn't get repositioned and so I'm thinking there must be a better way to do this. I'd read some people mentioning using a negative offset to move everything over but I wasn't sure how this would work with constraints as it needs to scale properly for each orientation. Is there an easier solution to this that I'm missing? Thank you.
It appears I was doing it the correct way. The missing piece regarding the divider between fields was setting the inset on iOS 7. You can do this in the viewdidload or viewwillload and set self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
You will need to add a check if running iOS 7 or newer as this is a new property I believe. A better option might be setting it in the storyboard by selecting the table view and then setting separator insets from default to custom.
Here is the layoutSubviews method that repositions imageView and textLabel. If you have a description add that as well.
- (void) layoutSubviews
{
[super layoutSubviews];
// Makes imageView get placed in the corner
self.imageView.frame = CGRectMake( 0, 0, 80, 80 );
// Get textlabel frame
//self.textLabel.backgroundColor = [UIColor blackColor];
CGRect textlabelFrame = self.textLabel.frame;
// Figure out new width
textlabelFrame.size.width = textlabelFrame.size.width + textlabelFrame.origin.x - 90;
// Change origin to what we want
textlabelFrame.origin.x = 90;
// Assign the the new frame to textLabel
self.textLabel.frame = textlabelFrame;
}

Centering and sizeToFit subview at run time and during orientation changes

The is the first of several problems I'm having setting up some UIViews and subviews. I have a UIView that is dynamically positioned on screen at run time. That UIView (master) contains another UIView (child) which wraps a UIImageView and a UILabel. Here are the requirements I have for this arrangement:
The child UIView must stay centered in the master UIView when the device rotates.
The text in the UILabel can be very long or very short and the child UIView with the image and text must still remain centered.
I would like to avoid subclassing UIView to handle this scenario and I would also like to avoid any frame/positioning code in willRotateToInterfaceOrientation. I'd like to handle all of this with some autoresizingMask settings in I.B. and maybe a little forced resizing code, if possible.
This is the arrangement of controls in Interface Builder(highlighted in red):
With Interface Builder, the autoresizingMask properties have been set like so, for the described controls
UIView (master): Flexible top margin, Flexible left margin, Flexible right margin, Flexible width
UIView (child): Flexible top margin, Flexible bottom margin, Flexible left margin, Flexible right margin, Flexible width, Flexible height. (All modes, except None)
UIImageView: Flexible right margin
UILabel: Flexible right margin
This is the view (red bar with image and text) after it's been added programmatically at run time while in portrait mode:
The master UIView's background is a light-red colored image. The child UIView's background is slightly darker than that, and the UILabel's background is even darker. I colored them so that I could see their bounds as the app responded to rotation.
It's clear to me that:
It is not centered but ...
After changing the text from it's default value in I.B from "There is no data in this map extent." to "TEST1, 123." the label contracts correctly.
This is the view after it's been added while in portrait and then rotated to landscape mode:
From here I can see that:
It is still not centered and perhaps at its original frame origin prior to rotation
The UIView (child) has expanded to fill more of the screen when it shouldn't.
The UIView (master) has properly expanded to fill the screen width.
This is the code that got me where I am now. I call the method showNoDataStatusView from viewDidLoad:
// Assuming
#define kStatusViewHeight 20
- (void)showNoDataStatusView {
if (!self.noDataStatusView.superview) {
self.noDataStatusView.frame = CGRectMake(self.mapView.frame.origin.x,
self.mapView.frame.origin.y,
self.mapView.frame.size.width,
kStatusViewHeight);
self.noDataStatusView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgRedStatus.png"]];
// Position the label view in the center
self.noDataStatusLabelView.center = CGPointMake(self.noDataStatusView.frame.size.width/2,
self.noDataStatusView.frame.size.height/2);
// Test different text
self.noDataStatusLabel.text = #"Testing, 123.";
// Size to fit label
[self.noDataStatusLabel sizeToFit];
// Test the status label view resizing
[self.noDataStatusLabelView resizeToFitSubviews];
// Add view as subview
[self.view addSubview:self.noDataStatusView];
}
}
Please note the following:
resizeToFitSubviews is a category I placed on UIView once I found that UIView's won't automatically resize to fit their subviews even when you call sizeToFit. This question, and this question explained the issue. See the code for the category, below.
I have thought about creating a UIView subclass that handles all this logic for me, but it seems like overkill. It should be simple to arrange this in I.B. right?
I have tried setting every resizing mask setting in the book, as well as adjusting the order in which the resizing of the label and view occur as well as the point at which the master view is added as a subview. Nothing seems to be working as I get odd results every time.
UIView resizeToFitSubviews category implementation method:
-(void)resizeToFitSubviews
{
float width = 0;
float height = 0;
// Loop through subviews to determine max height/width
for (UIView *v in [self subviews]) {
float fw = v.frame.origin.x + v.frame.size.width;
float fh = v.frame.origin.y + v.frame.size.height;
width = MAX(fw, width);
height = MAX(fh, height);
}
[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, width, height)];
}
What I want to know is why the UIView (child) is not properly centered after it's superview is added to the view hierarchy. It looks as though its got the proper width, but is somehow retaining the frame it had in I.B. when the label read "There is no data in this map extent."
I want to also know why it's not centered after device rotation and whether or not the approach I'm taking here is wise. Perhaps this is causing the other issues I'm having. Any UIView layout help here would be greatly appreciated.
Thanks!
If you are able to target iOS 6 you could use the new Auto Layout functionality to make this much much easier to manage - I've been reading a great tutorial by Ray Wenderlich that seems to be perfect to solve the problem you are seeing.
The problem here is that my UIView (master) does not layout it's subviews automatically when the device rotates and the "springs & struts" layout method used to position the image and interior UIView was inefficient. I solved the problem by doing two things.
I got rid of the internal UIView (child) instance, leaving only the UIView (master) and inside of that a UILabel and UIImageView.
I then created a UIView subclass called StatusView and in it I implement the layoutSubviews method. In its constructor I add a UIImageView and UILabel and position them dynamically. The UILabel is positioned first based on the size of the text and then the UIImageView is placed just to the left of it and vertically centered. That's it. In layoutSubviews I ensure that the positions of the elements are adjusted for the new frame.
Additionally, since I need to swap the background, message and possibly the image in some circumstances, it made sense to go with a custom class. There may be memory issues here/there but I'll iron them out when I run through this with the profiling tool.
Finally, I'm not totally certain if this code is rock solid but it does work. I don't know if I need the layout code in my init method, either. Layout subviews seems to be called shortly after the view is added as a subview.
Here's my class header:
#import <UIKit/UIKit.h>
typedef enum {
StatusViewRecordCountType = 0,
StatusViewReachedMaxRecordCountType = 1,
StatusViewZoomInType = 2,
StatusViewConnectionLostType = 3,
StatusViewConnectionFoundType = 4,
StatusViewNoDataFoundType = 5,
StatusViewGeographyIntersectionsType = 6,
StatusViewRetreivingRecordsType = 7
} StatusViewType;
#interface StatusView : UIView
#property (strong, nonatomic) NSString *statusMessage;
#property (nonatomic) StatusViewType statusViewType;
- (id)initWithFrame:(CGRect)frame message:(NSString*)message type:(StatusViewType)type;
#end
... and implementation:
#import "StatusView.h"
#define kConstrainSizeWidthOffset 10
#define kImageBufferWidth 15
#interface StatusView ()
#property (nonatomic, strong) UILabel *statusMessageLabel;
#property (nonatomic, strong) UIFont *statusMessageFont;
#property (nonatomic, strong) UIImage *statusImage;
#property (nonatomic, strong) UIImageView *statusImageView;
#end
#implementation StatusView
#synthesize statusMessageLabel = _statusMessageLabel;
#synthesize statusMessageFont = _statusMessageFont;
#synthesize statusImageView = _statusImageView;
#synthesize statusMessage = _statusMessage;
#synthesize statusViewType = _statusViewType;
#synthesize statusImage = _statusImage;
- (id)initWithFrame:(CGRect)frame message:(NSString *)message type:(StatusViewType)type {
self = [super initWithFrame:frame];
if (self) {
if (message != nil) {
_statusMessage = message;
_statusMessageFont = [UIFont fontWithName:#"Avenir-Roman" size:15.0];
CGSize constrainSize = CGSizeMake(self.frame.size.width - kImageBufferWidth - kConstrainSizeWidthOffset, self.frame.size.height);
// Find the size appropriate for this message
CGSize messageSize = [_statusMessage sizeWithFont:_statusMessageFont constrainedToSize:constrainSize];
// Create label and position at center of status view
CGRect labelFrame = CGRectMake(self.frame.origin.x,
self.frame.origin.y,
messageSize.width,
messageSize.height);
_statusMessageLabel = [[UILabel alloc] initWithFrame:labelFrame];
_statusMessageLabel.backgroundColor = [UIColor clearColor];
_statusMessageLabel.textColor = [UIColor whiteColor];
_statusMessageLabel.font = _statusMessageFont;
// Set shadow and color
_statusMessageLabel.shadowOffset = CGSizeMake(0, 1);
_statusMessageLabel.shadowColor = [UIColor blackColor];
// Center the label
CGPoint centerPoint = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
_statusMessageLabel.center = centerPoint;
// Gets rid of fuzziness
_statusMessageLabel.frame = CGRectIntegral(_statusMessageLabel.frame);
// Flex both the width and height as well as left and right margins
_statusMessageLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
// Set label text
_statusMessageLabel.text = _statusMessage;
[self addSubview:_statusMessageLabel];
}
self.statusViewType = type;
if (_statusImage != nil) {
// Create image view
_statusImageView = [[UIImageView alloc] initWithImage:_statusImage];
// Vertically center the image
CGPoint centerPoint = CGPointMake(_statusMessageLabel.frame.origin.x - kImageBufferWidth,
self.frame.size.height / 2);
_statusImageView.center = centerPoint;
[self addSubview:_statusImageView];
}
}
return self;
}
- (void)layoutSubviews {
CGSize constrainSize = CGSizeMake(self.frame.size.width - kImageBufferWidth - kConstrainSizeWidthOffset, self.frame.size.height);
// Find the size appropriate for this message
CGSize messageSize = [_statusMessage sizeWithFont:_statusMessageFont constrainedToSize:constrainSize];
// Create label and position at center of status view
CGRect labelFrame = CGRectMake(self.frame.origin.x,
self.frame.origin.y,
messageSize.width,
messageSize.height);
_statusMessageLabel.frame = labelFrame;
// Center the label
CGPoint centerPoint = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
_statusMessageLabel.center = centerPoint;
// Gets rid of fuzziness
_statusMessageLabel.frame = CGRectIntegral(_statusMessageLabel.frame);
if (_statusImageView != nil) {
// Vertically center the image
CGPoint centerPoint = CGPointMake(_statusMessageLabel.frame.origin.x - kImageBufferWidth,
self.frame.size.height / 2);
_statusImageView.center = centerPoint;
}
}
#pragma mark - Custom setters
- (void)setStatusMessage:(NSString *)message {
if (_statusMessage == message) return;
_statusMessage = message;
_statusMessageLabel.text = _statusMessage;
// Force layout of subviews
[self setNeedsLayout];
[self layoutIfNeeded];
}
- (void)setStatusViewType:(StatusViewType)statusViewType {
_statusViewType = statusViewType;
UIColor *bgColor = nil;
switch (_statusViewType) {
// Changes background and image based on type
}
self.backgroundColor = bgColor;
if (_statusImageView != nil) {
_statusImageView.image = _statusImage;
}
}
#end
Then in my view controller I can do this:
CGRect statusFrame = CGRectMake(self.mapView.frame.origin.x,
self.mapView.frame.origin.y,
self.mapView.frame.size.width,
kStatusViewHeight);
self.staticStatusView = [[StatusView alloc] initWithFrame:statusFrame message:#"600 records found :)" type:StatusViewRecordCountType];
self.staticStatusView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self.view addSubview:self.staticStatusView];
... and later on I can change it up by doing this:
self.staticStatusView.statusMessage = #"No data was found here";
self.staticStatusView.statusViewType = StatusViewNoDataFoundType;
Now I've got a reusable class rather than 12 UIView instances floating around my NIB with various settings and properties.

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