【发布时间】:2019-09-30 06:23:37
【问题描述】:
【问题讨论】:
-
可能是一些尺寸问题。
-
我已经使用 Interface Builder 设置了 stackView 的大小和约束。 @MojtabaHosseini
-
不要在标题中添加 Solved。
标签: ios swift uistackview
【问题讨论】:
标签: ios swift uistackview
@Nowonder 我只是重新创建您想要实现的目标。以下是步骤。
Interface Builder 添加一个 UIStackView 并添加所需的约束。添加以下代码。
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton()
button.setTitle("btn 1", for: .normal)
button.backgroundColor = UIColor.red
button.translatesAutoresizingMaskIntoConstraints = false
let button2 = UIButton()
button2.setTitle("btn 2", for: .normal)
button2.backgroundColor = UIColor.gray
button2.translatesAutoresizingMaskIntoConstraints = false
let button3 = UIButton()
button3.setTitle("btn 3", for: .normal)
button3.backgroundColor = UIColor.brown
button3.translatesAutoresizingMaskIntoConstraints = false
buttonStackView.alignment = .fill
buttonStackView.distribution = .fillEqually
buttonStackView.spacing = 8.0
buttonStackView.addArrangedSubview(button)
buttonStackView.addArrangedSubview(button2)
buttonStackView.addArrangedSubview(button3)
}
希望对你有帮助。
【讨论】:
我认为您需要再执行几个步骤才能开始显示该按钮。
将堆栈视图添加到当前视图的子视图
view.addSubview(buttonStackView)
现在每个视图按钮以及 stackView 都需要将 translatesAutoresizingMaskIntoConstraints 设置为 false。
button1.translatesAutoresizingMaskIntoConstraints = false
button2.translatesAutoresizingMaskIntoConstraints = false
buttonStackView.translatesAutoresizingMaskIntoConstraints = false
现在设置 stackView 约束
NSLayoutConstraint.activate([
buttonStackView.topAnchor.constraint(equalTo: view.topAnchor),
buttonStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
buttonStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
buttonStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor)])
您需要提供约束,或者可以覆盖 stackView 的固有大小。
override func intrinsicContentSize() -> CGSize
{
return CGSizeMake(200, 40)
}
由于UILabel 具有固有大小,因此按钮会显示,如果没有,您必须为它们设置约束以确保安全。
【讨论】:
解决了!
当我用实例方法init(type:)设置按钮的类型时按钮出现了
【讨论】: