CollecitonViewCell Dynamic With based on Autolayout label Text - swift

I Have a Horizontal Collection View with Cells containing a label that has auto layout that expands on the size of the cell view.
Im using Xcode 8 and Swift 3.
How can I make so that my cell size is dynamic based on the text? I mean, I want it to expand, so that Otro Text... Reads complete instead of how its shown right now with the dots.
As You can see on the screenshot, now my large text gets trimmed (The Collection view, is on the area that has the Texts: Todo, Otro Text... Test1).
Hope someone can help or orient me on finding a solution.

You need to make sure that the you add leading and trailing constraint to the label and do not add any width constraint.
Next step is to give an estimatedSize in you collectionViewLayout.
Example
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = CGSize(
width: 100, height: collectionView.bounds.size.height)
}

You need to set the estimatedItemSize in your UICollectionViewLayout to be able to enable self-sizing cells. It is not possible from Storyboards, only available through code.

Related

NSGridView custom view intrinsic size

I'm building a simple NSGridView, and want to have a custom NSView as each element of the grid. Eventually, each NSView will be a xib based label (NSTextField) centered in the NSView.
The problem I am having is with the intrinsic size of the NSView. I want to define the size of the NSView and have auto layout work based on that. I added this code to the custom view (labelView):
override var intrinsicContentSize: NSSize {
return NSSize(width:100, height:100);
};
And it is indeed called; but apparently ignored. As a test, I have on the same row some other labels, and the height for the row is always set to the largest of the row text heights (including the label in the custom view); but the length is set to the longest of column text fields, ignoring the label in the custom view. And anyway, I want to arbitrarily make the NSView a certain height and length, as I tried (but failed) to do with the intrinsicContentSize.
NSStackview seems to do the right thing; but NSGridView does not.
I can force the width of a particular column with
grid.column(at:0).width = 400;
but want I really want to do is define the size of the NSView, and let autolayout use that as a building block.
This strikes me as a conceptual error on my part, so if someone could explain these NSGridView-autolayout-NSView subtleties, I think many might benefit.
I was having the exact same issue, tried to use custom NSView's inside a NSGridView and couldn't get them to draw correctly. What finally worked for me was setting the following:
let gridSize = 5
let cellSize: CGFloat = 50
gridView.xPlacement = .fill // this was key part of the solution
gridView.yPlacement = .fill
for i in 0 ..< gridSize {
gridView.row(at: i).height = cellSize
gridView.column(at: i).width = cellSize
}
Note that I'm setting the size of each cell with the row height and column width of the NSGridView, and not using the NSView size, but this is the only way I got it working.

how can i set a dynamic height to collection view cell in swift?

HI everyone i'm looking for a working method that allows to dynamically set the height in my collectionViewCell because I tried various other answers without success.
My situation is pretty simple, I have a cell with an image, a UIlabel that displays username and a UILabel which contains some text. It's a common Comment cell for a post. My Screen
I tried this method but it doesn't work precisely because the height is too much compared to what is necessary
private func estimatedFrameForText(text: String) -> CGRect {
let size = CGSize(width: 270, height: 80)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
return NSString(string: text).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)], context: nil)
}
so my question is: there is a correct way to implement dynamic size on collection view cell like layout attribute wrap_content for Android?
UPDATE
I solved my problem using constraints and Automatic Estimated Size on Collection View. Setting up all constraints I forced the width of LABEl to be equal to the cell width and for the height I set the top and bottom spacing for the UILabel (with lines 0) to be equal to its content view (the one standard for the UiCollectionViewCell)
IT'S also important to set the size of the collection view cell to automatic
VIEW IMAGE

Automatic height adjustment for static UITableViewCell doesn't work

I have a static UITableView and I want to set the row height for three of the cells dynamically. So in viewDidLoad() I implemented the following code:
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableView.automaticDimension
I also implemented the heightForRowAt method:
(The first two cells of the first section should have a fixed height)
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 0 {
return CGFloat(85)
} else if indexPath.section == 0 && indexPath.row == 1 {
return CGFloat(145)
}
return UITableView.automaticDimension
}
This the result which I'm currently getting:
I changed the lines of the labels to 0, too and the constraints of the labels inside the cells are 0, 12, 0, 12 (top, right, bottom, left).
Does anybody know, why the cell in section 3 doesn't display the data in the right way?
Edit:
(How it looks after the implementation of the suggestion above)
Because sizeToFit() did not work for you, we are going to try something a little more involved.
The cell in section 3 is displaying the data the right way. This is because UILabels don't automatically adjust their height to accommodate the text inside. Here's what you need to do:
1. Create a height constraint for your UILabel In your interface builder, add a constraint for the height of the UILabel in section 3's cell. Connect this height constraint to your view controller's class via an #IBOutlet:
class YourViewController: UIViewController {
#IBOutlet var cellLabel: UILabel!
#IBOutlet var cellLabelHeight: NSLayoutConstraint!
...
}
2. Add String extension that calculates height I am unsure of where/when you are setting the text of the UILabel in question, but I know you are doing this somewhere as you have described it as being "dynamic". Whenever you do set the text of the UILabel in question, you now also need to change the constant of the height constraint that we made in order to accommodate this text. So, we need to be able to calculate the height of the UILabel based on its width and font. We can add an extension to String in order to do this:
extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
return ceil(boundingBox.height)
}
}
3. Set the height constraint's constant based off the UILabel's text The final step is to set the height of the UILabel height constraint we made by using the extension we just created:
cellLabel.text = "DummyDataDummyDataDummyDataDummyDataDummyDataDummyDataDummyDataDummyData"
//This will be called immediately after you set the text for the UILabel in question
cellLabelHeight.constant = cellLabel.text.height(withConstrainedWidth: cellLabel.frame.width, font: cellLabel.font)
The cell in section 3 is displaying the data the right way. Unless you tell it otherwise, a UILabel will not automatically adjust to accommodate the text within it.
What I need you to do is select the UILabel in question, then in the attributes inspector, set the Number of Lines to 0.
You also said that this UILabel is dynamic, meaning you are setting it's text somewhere in your code. Immediately after you set this UILabel's text, you are going to want to call myLabel.sizeToFit(). This should adjust the label's height to accommodate the text within.
If this doesn't work, I have another, more involved solution that should work for you.
Please look at the below;
Select your cellLabel and set the Lines value to 0:
Also apple says Self-Sizing
Summary :
lay out your table view cell’s content within the cell’s content view. To define the cell’s height, you need an unbroken chain of constraints and views (with defined heights) to fill the area between the content view’s top edge and its bottom edge. If your views have intrinsic content heights, the system uses those values. If not, you must add the appropriate height constraints, either to the views or to the content view itself.
Change the bottom constraint of the AuthorLabel from equal to Greater than or equal

Swift stackview add subview in center

I use this code for view nib to stackview
for index in 0..<4 {
let view = CategoryClass.createMyClassView()
view.myLabel.text = "Hello World!"
self.stackView.addArrangedSubview(view)
}
And I get below image :
But I want to add subview by category.xib height ( 40px per view ) not fill.
And set in center of parent
Like below :
Screenshot:
Please add Four label in Xib and after put in stackView and give spacing like 5, 10, 20 whatever you like
Please check screenshot and let me know if u have any problem related stackview i will help you
you need to delete the top and bottom constraints of the stackView. Or you can delete any one and make the other constraint in greater than or equal to form
This will solve your problem

Automatically adjust width of a view based NSTableView based on content

Title should read: Automatically adjust width of the containing NSWindow of a view based NSTableView based on NSTableCellView's NSTextField content intrinsic content size.
A bit like this other question, I would like to implement an autocompletion NSWindow with an NSTableView inside it that adjust to the width of the length of the available autocompletions implemented as NSTextField inside an NSTableCellView. Each autocompletion should obviously be displayed on one line...
The previous question has been answered but was only related to the hight of the NSTableView. I would like to know how to do the "same" for the width. I would like to implement the solution as much as possible using auto layout.
I've tried to set the horizontal "Content Hugging Priority" and the "Content Compression Resistance Priority" to the maximum of 1000 for each view element participating in the final display of the NSWindow. I was thinking that the intrinsic content size of the NSTextField would force all other elements to adjust but it does not work.
Setting the NSTableColumn width does not work either since the NSClipView of the NSScrollView is not modified by this width: the NSScrollView adjusts and creates horizontal scroll bars to cover the entire "document".
Here is a link to a sample project to demonstrate the problem:
sample project
Any help would be greatly appreciated!
I fixed the problem using this code with the scrollViewWidthConstraint being an IBOutlet to the NSScrollView width constraint, localTableView being an IBOutlet to the NSTableView and tableColumn being an IBOutlet to the NSTableColumn (the only one in my case).
Note: The linked project on GitHub has been updated with the changes.
override func viewDidLoad() {
super.viewDidLoad()
self.updateTable()
}
func updateTable() {
localTableView.reloadData()
var computedWidth: CGFloat = 0
for var row = 0; row < 10; row++ {
let tableCellView = self.tableView(localTableView, viewForTableColumn: tableColumn, row: row) as! NSTableCellView
computedWidth = max(computedWidth, tableCellView.textField!.intrinsicContentSize.width)
}
scrollViewWidthConstraint!.constant = computedWidth
scrollView.needsUpdateConstraints = true
}