我以编程方式制作的 StackView 如下所示:
两个 subview :
三个 subview :
四个 subview :
这是我的代码:
cameraButton.setImage(UIImage(named: "blueCamera"), for: .normal)
cameraButton.addTarget(self, action: #selector(cameraTapped), for: .touchUpInside)
cameraButton.widthAnchor.constraint(equalToConstant: 70.0).isActive = true
calenderButton.setImage(UIImage(named: "calender"), for: .normal)
calenderButton.addTarget(self, action: #selector(calanderTapped), for: .touchUpInside)
calenderButton.widthAnchor.constraint(equalToConstant: 70.0).isActive = true
stackView.frame = CGRect(x: 0, y: 0, width: scrollView.frame.size.width, height: scrollViewHeight)
stackView.axis = .horizontal
stackView.spacing = 5
stackView.semanticContentAttribute = .forceLeftToRight
stackView.alignment = .fill // .leading .firstBaseline .center .trailing .lastBaseline
stackView.distribution = .equalSpacing // .fillEqually .fillProportionally .equalSpacing .equalCentering
stackView.addArrangedSubview(calenderButton)
stackView.addArrangedSubview(cameraButton)
stackView.backgroundColor = UIColor(red: 0.161, green: 0.165, blue: 0.188, alpha: 1.00)
scrollView.addSubview(stackView)
问题是什么: StackView 未将 subview 向左对齐。
我想要实现的目标:
我希望所有 subview 都向左对齐,我尝试使用 stackView.semanticContentAttribute = .forceLeftToRight 来实现此目的,但这似乎没有取得多大成果。
最佳答案
设置:
stackView.alignment = .leading
并删除这个:
stackView.distribution = .equalSpacing
你的代码将是这样的:
cameraButton.setImage(UIImage(named: "blueCamera"), for: .normal)
cameraButton.addTarget(self, action: #selector(cameraTapped), for: .touchUpInside)
cameraButton.widthAnchor.constraint(equalToConstant: 70.0).isActive = true
calenderButton.setImage(UIImage(named: "calender"), for: .normal)
calenderButton.addTarget(self, action: #selector(calanderTapped), for: .touchUpInside)
calenderButton.widthAnchor.constraint(equalToConstant: 70.0).isActive = true
stackView.frame = CGRect(x: 0, y: 0, width: scrollView.frame.size.width, height: scrollViewHeight)
stackView.axis = .horizontal
stackView.spacing = 5
stackView.alignment = .leading
stackView.addArrangedSubview(calenderButton)
stackView.addArrangedSubview(cameraButton)
stackView.backgroundColor = UIColor(red: 0.161, green: 0.165, blue: 0.188, alpha: 1.00)
scrollView.addSubview(stackView)
关于ios - StackView 未以编程方式左对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53410848/