我正在尝试将UIStackview中的项目水平向左对齐。
无论如何以编程方式执行此操作?我试图通过故事板这样做,但没有成功。出于某种原因,UIStackView中的项目居中。
答案 0 :(得分:7)
如果使用StackView设置轴属性为" Horizontal", 我认为你不能将它对齐到左边。
但有一种方法可以让它在视觉上留下。
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(greaterThanOrEqualTo: view.trailingAnchor).isActive = true
答案 1 :(得分:4)
Swift 4.2 + iOS 12.1 已测试:
let stackView: UIStackView = UIStackView(frame: .zero)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.alignment = .leading // <- aligns each of your items to the left.
// further setup + setup constraints
// ...
答案 2 :(得分:1)
使用UIStackView.alignment
属性。
参考:https://developer.apple.com/reference/uikit/uistackview/1616243-alignment
答案 3 :(得分:1)
尝试在堆叠视图中添加一个空间视图,像这样
// To Make Our Buttons aligned to left We have added one spacer view
UIButton *spacerButton = [[UIButton alloc] init];
[spacerButton setContentHuggingPriority:UILayoutPriorityFittingSizeLevel forAxis:UILayoutConstraintAxisHorizontal];
[spacerButton setContentCompressionResistancePriority:UILayoutPriorityFittingSizeLevel forAxis:UILayoutConstraintAxisHorizontal];
[self.buttonsStackView addArrangedSubview:spacerButton];
并制作
self.buttonsStackView.distribution = UIStackViewDistributionFill;
答案 4 :(得分:0)
Trailing
Alignment
后,从下拉菜单中选择UIStackView.alignment
。tr
属性。答案 5 :(得分:0)
感谢你们的建议。我尝试使用UIStackView.alignment上的选项,但它从未真正按预期工作。最后,我弄乱了UIStackView的宽度,以达到理想的效果。
if(prdDTO.getShellIcn() == "Y")
{
let icon = UIImageView()
icon.contentMode = UIViewContentMode.scaleAspectFit
icon.image = #imageLiteral(resourceName: "Shellfish")
prdIngredients.addArrangedSubview(icon)
stackviewWidth += 25
}
if(prdDTO.getVegeIcn() == "Y")
{
let icon = UIImageView()
icon.contentMode = UIViewContentMode.scaleAspectFit
icon.image = #imageLiteral(resourceName: "Vege")
prdIngredients.addArrangedSubview(icon)
stackviewWidth += 25
}
if(prdDTO.getSpicyIcn() == "Y")
{
let icon = UIImageView()
icon.contentMode = UIViewContentMode.scaleAspectFit
icon.image = #imageLiteral(resourceName: "Spicy")
prdIngredients.addArrangedSubview(icon)
stackviewWidth += 25
}
prdIngredients.widthAnchor.constraint(equalToConstant: CGFloat(stackviewWidth))