I have a label in custom cell in table view.
I want to change cell height and also label height(at first I am showing only 2 line, I want to show more text) after user taped a cell,
I am able to change cell height based on cell content, but unfortunately I cannot change label height, :((
I've read tons of stackoverflow answers, but still nothing.
it is believed that this would work:
CGSize labelSize = [#"Hello World!" sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(label.frame.size.width,MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
but this is deprecated in iOS 7; can any one please help me in resizing my label in cell?
If you want the height of your label relative to the height of your cell and you use Storyboard, you should determine the size of your label with constraints in relation to the ContentView of the cell. Just set the top and bottom distance from your label to the ContentView and no additional height for the label.
If you dont know how to set Storyboard and constraints, this might help: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AutoLayoutbyExample/AutoLayoutbyExample.html
UITableViewCell lays out it's content in -layoutSubviews. Therefore, if you want to simply have a custom layout logic, you need to subclass UITableViewCell and override the -layoutSubviews method. It's a good idea to call super anyway before applying your logic, though.
You may use something like this to get UIlabel size
-(CGFloat)getLabelSize:(UILabel *)label fontSize:(NSInteger)fontSize
{
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:fontSize], NSFontAttributeName,
nil];
CGRect frame = [label.text boundingRectWithSize:CGSizeMake(270, 2000.0)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize size = frame.size;
return size.height;
}
Related
Situation
I have a (vertical) UIStackView containing both a plain UIView of height 50 (named sliderView) and a UILabel of height 36 defined in my storyboard. The label's alpha property is initially set to 0.0 to make it invisible.
In the controller's viewDidLoad I use UIViewController Containment to add another view controller's view to as a subview of sliderView. This new subview does not necessarily match sliderViews height. It might actually a fair bit taller.
At first, this setup looks fine. Once I make the label visible, I see that it still starts at a y-position of 50. So, the sliderView did not automatically stretch to use it's new child's height. Makes sense.
Question
I thought that I could easily just call sizeToFit on sliderView to make those two heights fit. Unfortunately, this does not seem to work. Am I misunderstanding something here? Thanks!
Use following method to get the CGSize required for NSString text.
- (CGSize)getHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
CGSize size = CGSizeZero;
if (text) {
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{ NSFontAttributeName:font } context:nil];
size = CGSizeMake(frame.size.width, frame.size.height+20.0f);
}
return size;
}
Here width parameter is the width of your label and font is the font specified for your label. Call CGSize.height to get the height.
I had a look on SO before asking this question. All the questions are about adjusting the height of a UILabel and not its width. I tried alternative methods but it did not work such as [label sizeToFit];. Is it possible to adjust the width of a label based on its text? I create my label in a UITableViewCell in story board. I want to be able to adjust its width based on the text that it is assigned. I dont want to resize the font size.
I set the text of the label in CellForRowAtIndexPath.
Examples would be great please.
Thanks in advance :)
Update 1: I have a custom cell that I am making in Storyboard so not programmatically. I set the contents of each cell in CellForRowAtIndexPath, for example, myLabel.text = recipe.name. The name label is quite small, however I would like to extend its width based on the length of the text, not truncate the tail or shrink the size of the text.
Update2: I have a lot of other UIElements in the cell. So I have a label in the top left, top right, bottom left, bottom right, and a picture in the middle, there default is 120 because they have a background color. I set it small the there is not a huge amount of empty space in the label.
Get the size of the string:
//Replace FLT_MAX with the maximum height/width you want the label to be, if no maximum leave as FLT_MAX.
CGSize stringSize = [YOUR_STRING sizeWithFont:YOUR_FONT constrainedToSize:CGSizeMake(FLT_MAX, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
Then size your label:
[YOUR_LABEL setFrame:CGRectMake(0, 0, stringSize.width, stringSize.height)];
In iOS 7 sizeWithFont is deprecated, use boundingRectWithSize instead:
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:YOUR_LABELS_FONT
forKey: NSFontAttributeName];
CGSize stringSize = [text boundingRectWithSize:CGSizeMake(FLT_MAX, FLT_MAX)
options:NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin
attributes:stringAttributes context:nil].size;
CGSize maxSize = CGSizeMake(250, CGFLOAT_MAX); //250 is max desired width
CGSize textSize = [Label.text sizeWithFont:Label.font constrainedToSize:maxSize];
Label.frame = CGRectMake(0, 0, textSize.width, 15); // desired Bounds
Using above code you can get frame size for perticular text, & then resize label accordingly
You don't need to set explicit width for UILabel. UILabel provides intrinsic content size when used with autolayout. If you add constraints that provide the label's x,y position(Top Space constraint + Leading Space constraint), autolayout will be able to determine its width height based on the content.
I have used UILabel in my app. It is working properly in portrait mode. But when I open my app in landscape mode it shows content in center of UIlabel. I have tried sizeToFit but it is not working. As soon as I increase uilabel's width spacing starts to arrive in uilabel.
My code:
self.contentLabel.text = labeltext;
[self.contentLabel setNumberOfLines:0];
[self.contentLabel sizeToFit];
I suspect your UILabel itself and not the text within it is actually aligning incorrectly upon rotation. Make sure the label stays aligned to the top of the view. Try:
self.contentLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight;
or
self.contentLabel.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
Edit: One other thought.
If auto layout's enabled and you're calling sizeToFit in viewDidLoad, perhaps the view is resizing after auto layout lays out the subviews. Try putting your code in viewDidLayoutSubviews instead.
If you add a UILabel with height bigger than the height of the text, it's normal if that happened and there is no way to change this alignement (Vertical center).
I have two solutions for this problem:
Work with constraint :
This constraint Greater than or equal is just magic.
If you create the label with the code I suggest to work with that:
UIFont *fontReceive = [UIFont systemFontOfSize:[UIFont systemFontSize]];
CGSize sizeText = [text sizeWithFont:fontReceive constrainedToSize:CGSizeMake(260, 9999) lineBreakMode:NSLineBreakByWordWrapping];
Hope that will help!
The best solution is to change the height of your cell according the the amount of text your are populating it with.
Please see this code below as an example.
NSString *content = **YOUR_STRING_LABEL_INTENDED_CONTENT**
CGSize maximumLabelSize = CGSizeMake(390, 1000); //For example - Put in your desired label width here and maximum size etc.
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13] forKey: NSFontAttributeName]; //This allows a calculation to be made of the space taken up, so if you're using a custom or large font it will calculate accordingly.
CGSize newExpectedLabelSize = [content boundingRectWithSize:maximumLabelSize options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size;
Now you can change the height of your label by using this next line, where label is the name of the label you made.
GCRect frame = label.frame;
frame.size.height = newExpectedLabelSize.height;
label.frame = frame;
I hope this helps, cheers, Jim.
I have a UITableViewCell subclass on which I'm using auto-layout, and I want to get the height of a UILabel subview once the auto-layout process has been completed.
I tried layoutSubviews and getting the frame property of my UILabel, but this seemed to be the old height of the label before it was recycled.
I then tried to override layoutIfNeeded but I found it was never called.
How can I get the frames of my UITableViewCell subviews once auto-layout is completed and the constraints have been applied? Surely this should be really simple!
Assuming that the label is an immediate subview of the table cell's content view, then my quess is that you could access the final, on-screen value of the label's bounds in the layoutSubviews method for the content view of the table cell (rather than the layoutSubviews method of the table cell itself).
However, if your label is not multi-lined, then simply grab the label's height from its attributedText property at anytime as follows:
NSAttributedString *attrString = label.attributedText;
CGFloat labelHeight = ceilf(attrString.size.height);
Alternatively, you could use the label's font property to determine the label's height (again, only if the label is not multi-lined):
UIFont *font = label.font;
CGFloat labelHeight = ceilf(font.lineHeight);
If your label is multi-lined, then the best choice for calculating the line height is as follows:
// but you have to know the label's width
CGFloat labelWidth = …
NSAttributedString *attrString = label.attributedText;
CGRect rect = [attrString boundingRectWithSize:CGSizeMake(labelWidth, FLT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
CGFloat labelHeight = ceilf(rect.size.height);
You would calculate the label's width manually. Often it's the main view's bounds width minus some fixed amount for horizontal spacing margins.
I've done a lot of reading already on this, but it's seems like there's no simple solution.
I'm trying to make an app that loads an NSArray of NSString comments to display in a UITableView. The comments all vary in size.
How can I get the cell to adjust its size to show the entire content of each comments?
I'm trying to find a simple solution without resorting to using magic CFloat numbers.
Is there a method in apple's API that allows me to calculate the needed height of the cell.detailTextLabel given an NSString comment and fixed width?
I think if I can calculate this height, all that's need is to set the height of the cell and the height of the row.
Not really sure what order to do this in since I've read the cell hasn't been created yet when heightForRow:AtIndexPath: gets called.
Calculate the height of the text in tableView:heightForRowAtIndexPath:
You need to use boundingRectWithSize:options:context: on iOS 7+ and sizeWithFont:forWidth:lineBreakMode: on iOS 6 and below. See the apple documentation for more information.
UIFont *font = [UIFont oka_commentLabelFont];
NSString *text = [self commentForIndexPath:indexPath];
CGFloat cellWidth = 300.f;
CGSize boundingSize = CGSizeMake(widthForCell, CGFLOAT_MAX);
CGSize size;
if ([text respondsToSelector:#selector(boundingRectWithSize:options:attributes:context:)]) {
size = [text boundingRectWithSize:boundingSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{ NSFontAttributeName : font }
context:nil].size;
} else {
size = [text sizeWithFont:font
constrainedToSize:boundingSize
lineBreakMode:NSLineBreakModeWordWrap];
}
return size.height;
You need to set the font to the same font you want to use on the cell. If you put this in a performUpdates block on the tableView then you will get a nice expanding animation.
Don't set the height of the cell, set the height of the row and the table view will do the rest.
To calculate the height of the text, ask a label with textRectForBounds:limitedToNumberOfLines:, or ask the string with one of the many methods like sizeWithFont:constrainedToSize:lineBreakMode:.
You may need to deal with padding around the label when compared to the size of the cell.
yes we can calculate the height of UILabel depending on the Font and line break mode.
UIFont * font = [UIFont systemFontOfSize:12.0];
CGSize newSize = [text sizeWithAttributes:#{NSFontAttributeName:font}];// You can add other attributes in dictionary to like line break mode.
Here you got new size for the text which will be in UILabel, now in hegihtForCellAtIndexPath method you can change the size of UITableViewCell. newSize.height is height you need for label, now you can add some value to it for offsets and return it.
Use
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}