Reputation: 1121
I'm adding labels to a stackview and I'm having trouble getting them to add to the top of the stackview rather than the middle.
I'm trying to accomplish this with the following code:
let textLabel = UILabel()
textLabel.textColor = .white
textLabel.widthAnchor.constraint(equalToConstant: self.stkCombatStackView.frame.width).isActive = true
textLabel.text = "This is a test"
textLabel.textAlignment = .left
stackview.addArrangedSubview(textLabel)
I want the labels to be added from top to bottom, how can I do this? without the weird spacing?
I have the spacing in the inspector set to 1
(I also have the stackview nested in a scrollview in the storyboard but i can't seem to scroll the stackview at all)
Upvotes: 2
Views: 4328
Reputation: 125017
I'm adding labels to a stackview and I'm having trouble getting them to add to the top of the stackview rather than the middle.
You should probably call insertArrangedSubview(_: at:)
instead of addArrangedSubview()
. The insert...
method lets you specify the index at which to insert the new view.
I want the labels to be added from top to bottom, how can I do this? without the weird spacing?
Are you sure you're using the right tool for the job? A stack view is good for containing a heterogeneous list of views in a fixed space, and it moves and/or resizes the views in the list to fill the view evenly. Take a look at the Distribution
values: you can either fill up the stack view by resizing the contents in a couple different ways, or you can spread the contents evenly across the height (or width) of the stack view. There's no option for just listing the contained views and leaving extra space at the bottom, which seems to be what you want.
Some options you could consider:
use a UICollectionView: Collection views are incredibly flexible, letting you lay out a list of items in any conceivable geometry; the provided layout manager will surely work for your needs, but if you don't like it you can write a layout manager of your own or use someone else's. UICollectionView is a subclass of UIScrollView, so scrolling is easy.
use a UITableView: A table view gives you a vertical list of (usually, but not necessarily, similar) cells that can contain anything you want, and that top to bottom behavior that you're looking for is inherent in the way a table works. UITableView is also a UIScrollView subclass.
roll your own: It's not that hard to create a view that simply contains a list of other views and lays them out according to any algorithm you like; if a table or collection won't work for your needs (which seems unlikely), writing your own container will work better than trying to force UIStackView into submission.
Upvotes: 2