In my awakeFromNib function, I have:
[_descriptionLabel setLineBreakMode:UILineBreakModeWordWrap];
[_descriptionLabel setNumberOfLines:10];
[_descriptionLabel sizeToFit];
and yet my label looks like this:
I know I'm setting these calls on the right label, because without these lines, the text appears vertically centered rather than aligned at the top. How can I make make my UILabel multiline?
I also tried setNumberOfLines:0.
SOLUTION I had set the width incorrectly in the xib file.
Try to set [_descriptionLabel setNumberOfLines:0]; which set the number of lines to auto.
It might be that sizeToFit is changing your label width, try to set it to explicit width, or remove it.
Just make sure that the initial width is set correctly. Then it should expand/shrink the height. But still the label won't be aligned to the top, it will be centered in its previous size after a call of sizeToFit (in case the new height is smaller than before, otherwise the origin will stay the same).
If you're not using AutoLayout, you need to measure text in code:
CGRect frame = _descriptionLabel.frame;
CGSize size = [_descriptionLabel.text sizeWithFont:_descriptionLabel.font constrainedToSize:CGSizeMake(frame.size.width, FLOAT_MAX) lineBreakMode:_descriptionLabel.lineBreakMode];
frame.size.height = MIN(MAX(size.height, frame.size.height), MAX_ALLOWED_HEIGHT);
_descriptionLabel.frame = frame;
Are you sure your awakeFromNib is in the right place. If it's in the view controller, it won't work. If it's in the implementation of a custom label, it should get called and that code should work:
#interface TestLabel : UILabel
#end
#implementation TestLabel
- (void)awakeFromNib
{
[self setLineBreakMode:UILineBreakModeWordWrap];
[self setNumberOfLines:10];
[self sizeToFit];
NSLog(#"Label: %#", NSStringFromCGRect(self.frame));
}
#end
Also, it's easier to set numberOfLines to 0, which means "any number of lines". And you shouldn't need to set UILineBreakModeWordWrap, since that's the default.
If you want to keep the code in the view controller, you can move it to viewDidLoad, which is the best place to do this kind of setup.
Related
Ok i have already gone through similar questions, but none of them helped.
I want to add a UILabel inside a UIScrollView so that the Label can be scrolled if the contents are large. Here is my code:
ViewController.h:
#interface ViewController : UIViewController
{
UILabel *myLabel;
UIScrollView *myScroll;
}
ViewController.h:
myLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+30, self.view.frame.size.width, self.view.frame.size.height)];
myScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+30, self.view.frame.size.width, self.view.frame.size.height)];
myLabel.backgroundColor = [UIColor yellowColor];
myLabel.text = #"Large random text";
[myLabel setNumberOfLines:0];
myLabel.lineBreakMode = NSLineBreakByWordWrapping;
[myLabel sizeToFit];
myScroll.contentSize = CGSizeMake(myLabel.frame.size.width,
myLabel.frame.size.height);
[myScroll addSubview:myLabel];
[self.view addSubview:myScroll];
I searched a lot on the internet but could not find a answer, can someone let me know what the issue is ?
Thank You !
I'm not sure how to do that, but I would like to suggest an alternative that may suit your needs. Use a UITextView, but set " [textView userInteractionEnabled:NO] " and it will act as a label, since it cannot be edited. It might end up looking like how you want.
Based on your comments, you need to size the label as needed so it is big enough for the given text. Then add the label to scroll view. Then set the scroll view's contentSize so it fits the whole label. This will ensure the scroll view allows you to scroll to see the whole label.
In addition to this, make sure the label's frame is relative to the scroll view and not to self.view. In other words, setting the label's frame's origin to 0,0 will put the label in the top left corner of the scroll view regardless of the position of the scroll view relative to its parent.
Try by replacing your contentSize like below code,
myScroll.contentSize = CGSizeMake(self.view.frame.size.width,self.view.frame.size.height + 100);
Hope it will work for u.
1.You have to use View(ContentView) to place the labels.
2.Add the ContentView into ScrollVIew.
3.Assign the ContentView Size whatever You Want
Go Through This Link,You Will get a Clear idea.
https://www.youtube.com/watch?v=UnQsFlMGDsI
Remove scrollView = [[UIScrollView alloc] init]; this is not necessary.Please Upvote if it helps.
Using autolayout I can't override my label in code. I've set the labels attributes in IB: Lines = 0, LineBreaks = Word Wrap, but I have my height set to a single line because due to what cell is selected determines what text goes in the label. So sometimes the label will only have one line.
In my viewDidLoad:
myLabel.text = #”blah, blah, blah….”;
[myLabel setLineBreakMode:NSLineBreakByWordWrapping];
myLabel.numberOfLines = 0; //have tried 1 but didn’t help
[myLabel sizeToFit];
This works on another project, but I wasn’t using AutoLayout. AutoLayout seems to override these settings.
I’ve even added
[myLabel setFrame:CGRectMake(20, 135, 280, 80);
but it doesn’t help.
Allow the intrinsic size of the label determine the height. You are correct that you need to set the numberOfLines property to 0. Since you are using AutoLayout, don't call sizeToFit and you need set the preferredMaxLayoutWidth of the label.
That's because your label's properties are set only once (in viewDidLoad), while the constraints from autolayout are applied everytime your view's layoutSubviews is called.
Also, using a line break mode that wraps the text won't work well with your UILabel if it's adjusting fonts, as per Apple's docs.
If this is a UIViewController, move the UILabel override code into - (void)viewDidLayoutSubviews, or if this is in a UIView, move the code to - (void)layoutSubviews.
Don't forget to call [super viewDidLayoutSubviews] or [super layoutSubviews] in those calls.
That being said, if you see yourself needing to override your constraints, either set up the constraints and properties to what you want in the nib file, otherwise use pure code to set up your label.
You need to set preferredMaxLayoutWidth to the maximum width your label can be. You should do this in viewWillLayoutSubviews.
I'm trying to show a long chunk of text inside a UILabel in one line.
The UILabel is a subview of UIScrollView so I can scroll and see the entire UILabel.
My problem is that the sizeToFit method only partialy works.
textLabel.attributedText = attributedString;
textLabel.numberOfLines = 1;
[textLabel sizeToFit];
textScrollView.contentSize = CGSizeMake(textLabel.frame.size.width, textLabel.frame.size.height);
The UIScrollView content size gets big enough to show the entire UILable, but for a line like:
so i'll try to share some of them here every once in a while."
The UILabel shows:
so i'll try to share som...
What am I doing wrong?
Turns out the code is just fine - but the Use Autolayout was checked.
Unchecked it - everything works just great...
If you want to achieve this with auto layout turned on it's simple. Just make sure you add numberOfLines
textLabel.adjustsFontSizeToFitWidth = YES;
textLabel.numberOfLines = 0;
Surprisingly, if you did not put a constraint on the label's width, this would work:
[textLabel.superview layoutSubviews];
I learned this by trial and error.
try
textLabel.adjustsFontSizeToFitWidth = YES;
textLabel.minimumFontScale = 0.5;
Since you have restricted your Label to show only one line of Text and truncate the rest , it is behaving the same
textLabel.attributedText = attributedString;
textLabel.numberOfLines = 0;
[textLabel sizeToFit];
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textScrollView.contentSize = CGSizeMake(textLabel.frame.size.width, textLabel.frame.size.height);
Hope it will help you
The most common reason for sizeToFit not working properly is the UILabel not having any autolayout constraints, for instance if you're implicitly relying on the view position remaining fixed relative to the top left. Adding any constraint at all (leading, top, centerY, anything) will fix it, presumably because it will result in layoutSubviews being called at some point, as suggested in Maxthon Chan's answer.
Following question is sort-of continuation of this one:
iOS: Multi-line UILabel in Auto Layout
The main idea is that every view is supposed to state it's "preferred" (intrinsic) size so that AutoLayout can know how to display it properly.
UILabel is just an example of a situation where a view cannot by itself know what size it needs for display. It depends on what width is provided.
As mwhuss pointed out, setPreferredMaxLayoutWidth did the trick of making the label span across multiple lines. But that is not the main question here. The question is where and when do I get this width value that I send as an argument to setPreferredMaxLayoutWidth.
I managed to make something that looks legit, so correct me if I am wrong in any way and tell me please if you know a better way.
In the UIView's
-(CGSize) intrinsicContentSize
I setPreferredMaxLayoutWidth for my UILabels according to self.frame.width.
UIViewController's
-(void) viewDidLayoutSubviews
is the first callback method I know where subviews of the main view are appointed with their exact frames that they inhabit on the screen. From inside that method I, then, operate on my subviews, invalidating their intrinsic sizes so that UILabels are broken into multiple lines based on the width that was appointed to them.
There's an answer this question on objc.io in the "Intrinsic Content Size of Multi-Line Text" section of Advanced Auto Layout Toolbox. Here's the relevant info:
The intrinsic content size of UILabel and NSTextField is ambiguous for multi-line text. The height of the text depends on the width of the lines, which is yet to be determined when solving the constraints. In order to solve this problem, both classes have a new property called preferredMaxLayoutWidth, which specifies the maximum line width for calculating the intrinsic content size.
Since we usually don’t know this value in advance, we need to take a two-step approach to get this right. First we let Auto Layout do its work, and then we use the resulting frame in the layout pass to update the preferred maximum width and trigger layout again.
The code they give for use inside a view controller:
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
[self.view layoutIfNeeded];
}
Take a look at their post, there's more information about why it's necessary to do the layout twice.
It seems annoying that a UILabel doesn't default to its width for the preferred max layout width, if you've got constraints that are unambiguously defining that width for you.
In nearly every single case I've used labels under Autolayout, the preferred max layout width has been the actual width of the label, once the rest of my layout has been performed.
So, to make this happen automatically, I have used a UILabel subclass, which overrides setBounds:. Here, call the super implementation, then, if it isn't the case already, set the preferred max layout width to be the bounds size width.
The emphasis is important - setting preferred max layout causes another layout pass to be performed, so you can end up with an infinite loop.
Update
My original answer appears to be helpful so I have left it untouched below, however, in my own projects I have found a more reliable solution that works around bugs in iOS 7 and iOS 8.
https://github.com/nicksnyder/ios-cell-layout
Original answer
This is a complete solution that works for me on iOS 7 and iOS 8
Objective C
#implementation AutoLabel
- (void)setBounds:(CGRect)bounds {
if (bounds.size.width != self.bounds.size.width) {
[self setNeedsUpdateConstraints];
}
[super setBounds:bounds];
}
- (void)updateConstraints {
if (self.preferredMaxLayoutWidth != self.bounds.size.width) {
self.preferredMaxLayoutWidth = self.bounds.size.width;
}
[super updateConstraints];
}
#end
Swift
import Foundation
class EPKAutoLabel: UILabel {
override var bounds: CGRect {
didSet {
if (bounds.size.width != oldValue.size.width) {
self.setNeedsUpdateConstraints();
}
}
}
override func updateConstraints() {
if(self.preferredMaxLayoutWidth != self.bounds.size.width) {
self.preferredMaxLayoutWidth = self.bounds.size.width
}
super.updateConstraints()
}
}
We had a situation where an auto-layouted UILabel inside a UIScrollView laid out fine in portrait, but when rotated to landscape the height of the UILabel wasn't recalculated.
We found that the answer from #jrturton fixed this, presumably because now the preferredMaxLayoutWidth is correctly set.
Here's the code we used. Just set the Custom class from Interface builder to be CVFixedWidthMultiLineLabel.
CVFixedWidthMultiLineLabel.h
#interface CVFixedWidthMultiLineLabel : UILabel
#end
CVFixedWidthMultiLineLabel.m
#implementation CVFixedWidthMultiLineLabel
// Fix for layout failure for multi-line text from
// http://stackoverflow.com/questions/17491376/ios-autolayout-multi-line-uilabel
- (void) setBounds:(CGRect)bounds {
[super setBounds:bounds];
if (bounds.size.width != self.preferredMaxLayoutWidth) {
self.preferredMaxLayoutWidth = self.bounds.size.width;
}
}
#end
Using boundingRectWithSize
I resolved my struggle with two multi-line labels in a legacy UITableViewCell that was using "\n" as a line-break by measuring the desired width like this:
- (CGFloat)preferredMaxLayoutWidthForLabel:(UILabel *)label
{
CGFloat preferredMaxLayoutWidth = 0.0f;
NSString *text = label.text;
UIFont *font = label.font;
if (font != nil) {
NSMutableParagraphStyle *mutableParagraphStyle = [[NSMutableParagraphStyle alloc] init];
mutableParagraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = #{NSFontAttributeName: font,
NSParagraphStyleAttributeName: [mutableParagraphStyle copy]};
CGRect boundingRect = [text boundingRectWithSize:CGSizeZero options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
preferredMaxLayoutWidth = ceilf(boundingRect.size.width);
NSLog(#"Preferred max layout width for %# is %0.0f", text, preferredMaxLayoutWidth);
}
return preferredMaxLayoutWidth;
}
Then calling the method was then as simple as:
CGFloat labelPreferredWidth = [self preferredMaxLayoutWidthForLabel:textLabel];
if (labelPreferredWidth > 0.0f) {
textLabel.preferredMaxLayoutWidth = labelPreferredWidth;
}
[textLabel layoutIfNeeded];
As I'm not allowed to add a comment, I'm obliged to add it as an answer.
The version of jrturton only worked for me if I call layoutIfNeeded in updateViewConstraints before getting the preferredMaxLayoutWidth of the label in question.
Without the call to layoutIfNeeded the preferredMaxLayoutWidth was always 0 in updateViewConstraints. And yet, it had always the desired value when checked in setBounds:. I didn't manage to get to know WHEN the correct preferredMaxLayoutWidth was set. I override setPreferredMaxLayoutWidth: on the UILabel subclass, but it never got called.
Summarized, I:
...sublcassed UILabel
...and override setBounds: to, if not already set, set preferredMaxLayoutWidth to CGRectGetWidth(bounds)
...call [super updateViewConstraints] before the following
...call layoutIfNeeded before getting preferredMaxLayoutWidth to be used in label's size calculation
EDIT: This workaround only seems to work, or be needed, sometimes. I just had an issue (iOS 7/8) where the label's height were not correctly calculated, as preferredMaxLayoutWidth returned 0 after the layout process had been executed once. So after some trial and error (and having found this Blog entry) I switched to using UILabel again and just set top, bottom, left and right auto layout constraints. And for whatever reason the label's height was set correctly after updating the text.
As suggested by another answer I tried to override viewDidLayoutSubviews:
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
_subtitleLabel.preferredMaxLayoutWidth = self.view.bounds.size.width - 40;
[self.view layoutIfNeeded];
}
This worked, but it was visible on the UI and caused a "visible flicker" i.e. first the label was rendered with the height of two lines, then it was re-rendered with the height of only one line.
This was not acceptable for me.
I found then a better solution by overriding updateViewConstraints:
-(void)updateViewConstraints {
[super updateViewConstraints];
// Multiline-Labels and Autolayout do not work well together:
// In landscape mode the width is still "portrait" when the label determines the count of lines
// Therefore the preferredMaxLayoutWidth must be set
_subtitleLabel.preferredMaxLayoutWidth = self.view.bounds.size.width - 40;
}
This was the better solution for me, because it did not cause the "visual flickering".
A clean solution is to set rowcount = 0 and to use a property for the heightconstraint of your label. Then after the content is set call
CGSize sizeThatFitsLabel = [_subtitleLabel sizeThatFits:CGSizeMake(_subtitleLabel.frame.size.width, MAXFLOAT)];
_subtitleLabelHeightConstraint.constant = ceilf(sizeThatFitsLabel.height);
-(void) updateViewConstraints has a problem since iOS 7.1.
In iOS 8, you can fix multi-line label layout problems in a cell by calling cell.layoutIfNeeded() after dequeuing and configuring the cell. The call is harmless in iOS 9.
See Nick Snyder's answer. This solution was taken from his code at https://github.com/nicksnyder/ios-cell-layout/blob/master/CellLayout/TableViewController.swift.
I have a UIButton and it can change the title at the runtime. Therefore, I want to increase the UIButton height depend on the title text for display full text by using AutoLayout.
I can increase the UILabel height by set the height constraint to "Greater than or Equal" but it not work with UIButton.
I have used [myButton sizeToFit] but it only increase the UIButon width (not increase height).
My current UIButton properties now is
- constraint height: 30
- leading : 15
- trailing: 15
- top: 5
- fontsize: 12
UPDATE
I created an IBOutlet for constraint height of UIButton for changing the height as #NSNood said.
Then I need to use \n in title text to split line.
But I don't know where should I put the \n?
Here is the Button that I want in portrait
Here is the Button that I want in landscape
How can I determine the place to put \n?
Please guide me how to achieve it with AutoLayout. Any help would be appreciated.
Sorry that I didn't follow the post, lately and thus am coming up with a real late solution. Still I'm writing the answer as a reference, if someone might find it useful in future.
First of all let's show the storyboard configuration for the button. Those are depicted in the following pictures:
The picture shows that I have added only left, top and right constraints for the button and nothing else. This allows the button to have some intrinsicContentSize for it's height but it's width is still determined by it's left and right constraints.
The next phase is to write some ViewController class that shall contain the button. In my VC, I have created an outlet for the button by name button:
#property(nonatomic,weak) IBOutlet UIButton* button;
and has attached it to the storyboard button. Now I have overridden two methods, namely, viewDidLoad and viewWillLayoutSubviews like below:
-(void)viewDidLoad {
[super viewDidLoad];
self.button.titleLabel.numberOfLines = 0;
self.button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
}
-(void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
[self.button setTitle:#"Chapter One\n "
"A Stop on the Salt Route\n "
"1000 B.C.\n "
"As they rounded a bend in the path that ran beside the river, Lara recognized the silhouette of a fig tree atop a nearby hill. The weather was hot and the days were long. The fig tree was in full leaf, but not yet bearing fruit." forState:UIControlStateNormal];
}
The viewDidLoad method ensures the titleLabel (the label that
holds button text) is multiline and if some large text comes to it,
it wraps the text by wrapping words.
The viewWillLayoutSubviews method ensures button layouting process
occurs whenever bounds of the main view change, e.g. due to the
change of interface orientation.
The final and the most effective part is to manually handle the layout process for the button. For this purpose, we need to subclass UIButton. I have written a subclass named MyButton that inherits from UIButton and you might use whatever name you like. Set this as the custom class for the button in Identity Inspector.
The subclass overrides two methods, namely, intrinsicContentSize and layoutSubviews. The class body looks something like the following:
#import "MyButton.h"
#implementation MyButton
-(CGSize)intrinsicContentSize {
return [self.titleLabel sizeThatFits:CGSizeMake(self.titleLabel.preferredMaxLayoutWidth, CGFLOAT_MAX)];;
}
-(void)layoutSubviews {
self.titleLabel.preferredMaxLayoutWidth = self.frame.size.width;
[super layoutSubviews];
}
#end
The UIButon subclass takes the ownership of the layout process by overriding layoutSubviews method. The basic idea here is to determine the button width, once it has been layout. Then setting the width as preferredMaxLayoutWidth (the maximum width for layouting engine, that a multiline label should occupy) of it's child titleLabel (the label that holds button text). Finally, returning an intrinsicContentSize for the button based on it's titleLabel's size, so that the button fully wraps it's titleLabel.
The overridden layoutSubviews is called when the button is already
layed out and it's frame size is determined. At it's first step,
button's rendered width is set as preferredMaxLayoutWidth of the
button's titleLabel.
The second step re-invokes the layouting engine by calling [super
layoutSubviews], so that the buttons intrinsicContentSize is
re-determined based on it's titleLabel's
preferredMaxLayoutWidth, which is set to buttons rendered width,
by now.
In the overridden intrinsicContentSize method we return the
minimum fitting size for the button that fully wraps it's
titleLabel with preferredMaxLayoutWidth set. We use
sizeThatFits fits method on the button's titleLabel and that
simply works as titleLabel doesn't follow any constraint based
layout.
The outcome should be something similar to that you might have required.
Feel free to let me know about any other clarification/concern.
Thanks.
Ayan Sengupta solution in Swift, with support for contentEdgeInsets (thanks Claus Jørgensen):
(You may also further customize the code to take titleEdgeInsets into account if needed)
Subclass your UIButton to take the ownership of the layout process:
/// https://stackoverflow.com/a/50575588/1033581
class AutoLayoutButton: UIButton {
override var intrinsicContentSize: CGSize {
var size = titleLabel!.sizeThatFits(CGSize(width: titleLabel!.preferredMaxLayoutWidth - contentEdgeInsets.left - contentEdgeInsets.right, height: .greatestFiniteMagnitude))
size.height += contentEdgeInsets.left + contentEdgeInsets.right
return size
}
override func layoutSubviews() {
titleLabel?.preferredMaxLayoutWidth = frame.size.width
super.layoutSubviews()
}
}
Use this class in your storyboard, and set constraints for Leading, Trailing, Top, Bottom. But don't set any Height constraint.
An alternative without subclassing is to add a wrapper view as suggested by Bartłomiej Semańczyk answer and Timur Bernikowich comment.
The point is that if you set sizeToFit property, then the text will always be in one line and the width of the button will increase unless you put a next-line sign \n to explicitly say that you want it to be several lines.
You put '\n' in the end of the first line like "line \n line" which represents
line
line
If you want to have two different string values (with \n positioned differently) for Portrait and Landscape you can check the orientation condition using UIDeviceOrientation (UIDevice.currentDevice.orientation) described here and set a string value depending on the orientation of the device
There is a way I always used:
Add another reference UILabel which lineNumber=0 and the same width with the target button.
Do not set height constraint for the ref-UILable, and should set a height constraint for the button to adjust its height
Set the same text to the ref UILabel with the button.titleLable, sizeTofit it and get its frame.size.height
Use the height value to the height constraint of the target button. (Of course, the button.titleLabel linenumber should be set to 0 or more lines)
Done. :)
PS1. This way can be used for the button and ref-label in a scrollview.
PS2. In some case, we can not get the correct height of the ref-label because it cannot gain a correct frame.width in scrollview, especially when we use the trailling constraint. We could consider to define a fixed width to the ref-label before sizeTofit and obtain the correct height for target button use.