I have a UICollectionView cell, which has multiple items
I need to implement its dynamic height depending on the data of 1st bold label
I have tried multiple code snippets but not working for my case.
as most of them are checking a specific label height and assigning it to the cell size..
Thanks
I have written this function in Xamarin.iOS to calculate the height of cell.
Hope this will help you.
CGRect GetRectOfItemNameLabel(ActivityTaskModel item , UITableView tableView)
{
nfloat width = tableView.Frame.Width;
UIStringAttributes attrs1 = new UIStringAttributes ();
attrs1.Font = UIFont.FromName("Helvetica", 17);
CGRect frameName = ((NSString)item.TaskDescription).GetBoundingRect (new CGSize (width, 100000), NSStringDrawingOptions.UsesLineFragmentOrigin, attrs1, null);
return frameName;
}
Make sure you don't provide any height constraint to that label/TextView.
Note : If your text is larger then rather than using Label use TextView
Related
I created a tableview cell using stactView with multiple labels so they can automatically adjust the dynamic content of the label. And it is perfectly working in the tableview.
But now I'm in need to use the same cell in a view with dynamic content.
I'm calling the cell is like
NSArray * arr =[[NSBundle mainBundle] loadNibNamed:#"StaticCalloutView" owner:nil options:nil];
StaticCalloutView * staticView = [arr firstObject];
staticView.imageView.image = [UIImage imageNamed:#"permit-pin.png"];
staticView.lblTitle.text = (NSString *) [feature attributeForKey:ATTRIBUTE_DESCRIPTION];
staticView.lblDesc.text = (NSString *) [feature attributeForKey:ATTRIBUTE_LOCATION];
But the problem here is it is not resizing itself in this case.
For the tableview i use the AutomaticDimension but what should i use in this case so that the view I'm calling will expand or compress accrding to the data pass to the labels. ??
One thing I noticed during debugging when I remove the bottom constraint of the topmost stackView then the stackview resizes itself with the content but the view in which it is showing didnt.
You need to override in your StaticCalloutView class the intrinsicContentSize variable this variable allow the view autoresize according the content or whatever criteria you use, there are some UIControls that have this method implemented by default UILabel and UIButton are two examples
This is an example of intrinsic contentSize implementation, note that this CustomAutoresizableView will grow according to the number of items in arrayOfValues multiplied by 40 in height
class CustomAutoresizableView: UIView {
var arrayOfValues : [Int] = []{
willSet
{
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize
{
get
{
return CGSize(width: self.frame.width, height: CGFloat(self.arrayOfValues.count * 40))
}
}
}
The Apple documentation says
For all alignments except the fill alignment, the stack view uses each
arranged view’s intrinsicContentSize property when calculating its
size perpendicular to the stack’s axis
The reason why it is not expanding is because of ambiguity in the width for the label. UILabel needs to know width to properly layout in multiple lines. Check and try these options
Set numberOfLines property of UILabel to 0.
Set lineBreak property to WordWrap
Set the width constraint for the detail
label or the view containing the labels.
So I'm trying to use the built-in UITableViewCell styles - specifically UITableViewCellStyleSubtitle - with a (single) line textLabel but multiline detailTextLabel. But the (auto) calculated cell height is consistently too short, and appears to ignore that there is more than 1 line of detail.
I've tried using numberOfLines=0, estimatedRowHeight, UITableViewAutomaticDimension, preferredMaxWidthLayout, etc, but in all the permutations the behavior - indeed for all the UITableViewCell styles - is it appears the UITableViewAutomaticDimension cell height calculation will correctly account for a multiline textLabel (yay!), but incorrectly assumes the detailTextlabel is at most single line (nay!). Consequently, cells with a multiline detailTextLabel are too short, and hence the cell content spills over the top and bottom of the cell.
I've posted a quick test app showing this behavior on GitHub here. Adding additional lines of text is fine - all the cell styles appropriately increase in height to accommodate - but adding additional lines of detail does nothing to change the cell height, and quickly causes the content to spill over; the text+detail are themselves laid out correctly, and together centered correctly over the middle of the cell (so in that sense layoutSubviews is working correctly), but the overall cell height itself is unchanged.
It almost seems like there are no actual top & bottom constraints between the cell.contentView and the labels, and instead the cell height is being calculated directly from the height of the (possibly multi-line) textLabel and (only single-line) detailTextLabel, and then everything is centered over the middle of the cell... Again, multiline textLabel is fine, and I'm doing nothing different between the textLabel and detailTextLabel, but only the former (correctly) adjusts the cell height.
So my question is, if it is possible to use the built-in UITableViewCell styles to reliably display multiline detailTextLabels, or is it simply not possible and you need to create a custom subclass instead? [or, almost equivalently, without having to override layoutSubviews in a subclass and rewire all the constraints manually].
[4 May 2016] Conclusion: as of iOS9 multi-line detailTextLabels dont work as expected with UITableViewAutomaticDimension; the cell will be consistently too short and the text/detail will spill over the top and bottom. Either you must manually compute the correct cell height yourself, or create and layout your own equivalent custom UITableViewCell subclass, or (see my answer below) subclass UITableViewCell and fix systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority: to return the correct height [recommended]
Further investigations (see UITableViewCellTest) indicate that when UITableViewAutomaticDimension is enabled the system calls -systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority: to calculate the cell height, and that this pretty much ignores the height of the detailTextLabel in its computation (bug !?). As a result, for UITableViewCellStyleSubtitle the cell height is always going to be too short [a single-line detailTextLabel may not quite spill over the cell, but that's only because of the existing top and bottom margins], and for UITableViewCellStyleValue1 or UITableViewCellStyleValue2 the height will be too short whenever the detailTextLabel is taller (eg more lines) than the textLabel. This is all a moot point for UITableViewCellStyleDefault which has no detailTextLabel.
My solution was to subclass and fix with:
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize
withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority
verticalFittingPriority:(UILayoutPriority)verticalFittingPriority
{
// Bug finally fixed in iOS 11
if ([UIDevice.currentDevice.systemVersion compare:#"11" options:NSNumericSearch] != NSOrderedAscending) {
return [super systemLayoutSizeFittingSize:targetSize
withHorizontalFittingPriority:horizontalFittingPriority
verticalFittingPriority:verticalFittingPriority];
}
[self layoutIfNeeded];
CGSize size = [super systemLayoutSizeFittingSize:targetSize
withHorizontalFittingPriority:horizontalFittingPriority
verticalFittingPriority:verticalFittingPriority];
CGFloat detailHeight = CGRectGetHeight(self.detailTextLabel.frame);
if (detailHeight) { // if no detailTextLabel (eg style = Default) then no adjustment necessary
// Determine UITableViewCellStyle by looking at textLabel vs detailTextLabel layout
if (CGRectGetMinX(self.detailTextLabel.frame) > CGRectGetMinX(self.textLabel.frame)) { // style = Value1 or Value2
CGFloat textHeight = CGRectGetHeight(self.textLabel.frame);
// If detailTextLabel taller than textLabel then add difference to cell height
if (detailHeight > textHeight) size.height += detailHeight - textHeight;
} else { // style = Subtitle, so always add subtitle height
size.height += detailHeight;
}
}
return size;
}
And in the view controller:
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.estimatedRowHeight = 44.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
}
You can pull the full subclass from here: MultilineTableViewCell
So far this fix appears to work well, and has let me successfully use the built-in UITableViewCellStyles with multiline text and details, in self-sizing cells with dynamic type support. This avoids the trouble (and mess) of manually computing the desired cell heights in tableView:heightForRowAtIndexPath:, or having to create custom cell layouts.
[(PARTLY)FIXED IN iOS11]
Apple finally fixed this bug in iOS11 (but apparantly only for UITableViewCellStyleSubtitle). I've updated my solution to only apply the necessary correction to pre-11 devices (otherwise you'll end up with extra space top and bottom of your cell!).
#tiritea 's answer in Swift 3 (Thanks again! :D)
// When UITableViewAutomaticDimension is enabled the system calls
// -systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority: to calculate the cell height.
// Unfortunately, it ignores the height of the detailTextLabel in its computation (bug !?).
// As a result, for UITableViewCellStyleSubtitle the cell height is always going to be too short.
// So we override to include detailTextLabel height.
// Credit: http://stackoverflow.com/a/37016869/467588
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
self.layoutIfNeeded()
var size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
if let textLabel = self.textLabel, let detailTextLabel = self.detailTextLabel {
let detailHeight = detailTextLabel.frame.size.height
if detailTextLabel.frame.origin.x > textLabel.frame.origin.x { // style = Value1 or Value2
let textHeight = textLabel.frame.size.height
if (detailHeight > textHeight) {
size.height += detailHeight - textHeight
}
} else { // style = Subtitle, so always add subtitle height
size.height += detailHeight
}
}
return size
}
It looks like Apple has resolved this bug in iOS 11.
Swift 3
After reading various answers, I have used following method for get ride of detail text label UITableViewAutomaticDimension issue . Use Basic style cell with title label only and use attributed string for Text and detail text view. Don't forget to Change tableview cell style from Subtitle to Basic.
func makeAttributedString(title: String, subtitle: String) -> NSAttributedString {
let titleAttributes = [NSFontAttributeName: UIFont.preferredFont(forTextStyle: .headline), NSForegroundColorAttributeName: UIColor.purple]
let subtitleAttributes = [NSFontAttributeName: UIFont.preferredFont(forTextStyle: .subheadline)]
let titleString = NSMutableAttributedString(string: "\(title)\n", attributes: titleAttributes)
let subtitleString = NSAttributedString(string: subtitle, attributes: subtitleAttributes)
titleString.append(subtitleString)
return titleString
}
How to use in cellforrowatindexpath
cell.textLabel?.attributedText = makeAttributedString(title: "Your Title", subtitle: "Your detail text label text here")
Add Following lines in viewdidload
YourTableView.estimatedRowHeight = UITableViewAutomaticDimension
YourTableView.rowHeight = UITableViewAutomaticDimension
YourTableView.setNeedsLayout()
YourTableView.layoutIfNeeded()
From my experience the built in cells don't support auto resize with constraints, I think the best solution is to create a custom cell, it really takes a couple of minutes and you don't need to override layoutSubview, it is really simple .
Just change the type of the cell in the IB to custom, drag a label , set constraints (in the IB), set number of rows , create a subclass, change the cells class in the IB to your subclass, create an outlet in the subclass and that's most of the work,
I am sure there are a lot of tutorials on the net you can follow.
I have a problem with uisplitviewcontroller. master controller is a tabbarviewcontroller and child controller is just a webview.. So I show some document on the rightside and leftside i want to show document information in tableview.
As you see on the figure (i draw red rectangles), some text are not fit on the cell, and i need to scroll it, but as a default, there is no horizontal scrolling in tableview. How to solve this problem?
I am using xamarin.ios but you can provide me obj-C or swift code or algorithm.
1 you can increase the tableView width
2 you can place UIScrollView on the cell and other labels move in that scrollView, then you can scroll the content of each cell
3 you can use UITextView in readonly mode instead of the second label in the cell, the scroll should be available automatically for the last text
I solved the problem.. Thank you Igor for the idea..
public CustomInformationCell (NSString cellId,int maxLenght,int totalCharLenght)
: base(UITableViewCellStyle.Default, cellId)
{
_maxLength = maxLenght; //max lenght is the longest label length in order to making alignment
SelectionStyle = UITableViewCellSelectionStyle.None;
Accessory = UITableViewCellAccessory.None;
ContentView.BackgroundColor = UIColor.White;
detail = new UILabel();
caption = new UILabel ();
caption.TextColor = UIColor.FromRGB (48,110,255);
_scrollView = new UIScrollView {
Frame = new CGRect (0, 0, ContentView.Bounds.Width, ContentView.Bounds.Height),
ContentSize = new CGSize (ContentView.Bounds.Width + totalCharLenght, ContentView.Bounds.Height),
BackgroundColor = UIColor.White,
AutoresizingMask = UIViewAutoresizing.FlexibleWidth
};
_scrollView.AddSubview (caption);
_scrollView.AddSubview (detail);
ContentView.AddSubviews(new UIView[] {_scrollView});
//ContentView.AddSubviews(new UIView[] {caption, detail});
}
I m working on an app where I calculate the height of tableview cell(custom cell) dynamically.The height is calculated perfectly but the label in the cell is truncated. I also tried to set the label's height but still it shows truncated text.
In above screenshot you can see that the long text is not completely shown,
I tried setting the label's height programmatically but it does not work.
Below is the code for setting the height:
let attributes = NSMutableDictionary()
attributes.setValue(MyFonts.HELVETICA_NEUE_REGULAR_15, forKey: NSFontAttributeName)
var cellSize = labelText!.boundingRectWithSize(labelSize!, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
labelHeight = cellSize.size.height
customCell?.subtitleLabel?.frame.size.height = labelHeight;
Kindly suggest any solution for this.
If your cell is created with auto layout you need to set
customCell?.subtitleLabel?.setTranslatesAutoresizingMaskIntoConstraints(true)
Here you have to take care of some points.
Need to override layoutSubviews() in custom cell, so that you can set frame for that label text
Number of line for label should be zero
Dynamic calculate the height of label
Dynamic cell height
I have created demo for dynamic cell.
Sample demo
I'm trying calculate the height of each cell in my table. Currently, I use this.
CGSize maximumSize = CGSizeMake(tableView.frame.size.width, UILayoutFittingCompressedSize.height);
CGFloat height = [offscreenCell.contentView systemLayoutSizeFittingSize:maximumSize].height;
return height;
The problem is that the cell has many labels with a date string label at the top of it and then multiple labels added below that listing the items for that date. This date label is being cut off for some reason in some of the cells. I think it might have to do with the label's string wrapping to a second line and the height not being calculated correctly.
Any ideas? Thank you.
Get a cell, set it's properties(date label, etc.) call layoutIfNeeded and then calculate this height:
MyCustomCell* cell = [myTableView dequeReusableCellWithIdentifier:#"CellId"];
for( NSString* text in arrayOfTexts )
{
[cell setDateLabelText:text];
[cell layoutIfNeeded];
CGSize maximumSize = CGSizeMake(tableView.frame.size.width, UILayoutFittingCompressedSize.height);
CGFloat height = [offscreenCell.contentView systemLayoutSizeFittingSize:maximumSize].height;//now store this height and use it in height for row at index path
}