如何使用swift中的for循环将按钮添加到stackview?
我已经使用xib创建了一个stackview,并希望通过编程方式向其添加按钮。我试图创建按钮并将ArrangedSubview添加到stackview,但按钮未显示。 我的代码:如何使用swift中的for循环将按钮添加到stackview?,swift,loops,button,xib,uistackview,Swift,Loops,Button,Xib,Uistackview,我已经使用xib创建了一个stackview,并希望通过编程方式向其添加按钮。我试图创建按钮并将ArrangedSubview添加到stackview,但按钮未显示。 我的代码: 根据文件 定位和调整堆栈视图的大小 尽管堆栈视图允许您在不直接使用自动布局的情况下布局其内容,但仍然需要使用自动布局来定位堆栈视图本身。通常,这意味着至少固定堆栈视图的两个相邻边以定义其位置 下面是一个工作示例 import UIKit import PlaygroundSupport class MyViewCon
根据文件 定位和调整堆栈视图的大小 尽管堆栈视图允许您在不直接使用自动布局的情况下布局其内容,但仍然需要使用自动布局来定位堆栈视图本身。通常,这意味着至少固定堆栈视图的两个相邻边以定义其位置 下面是一个工作示例
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
self.view = view
let stackView = UIStackView()
for item in 1...5 {
let button = UIButton()
button.setTitle("Button \(item)", for: .normal)
button.backgroundColor = .red
stackView.addArrangedSubview(button)
}
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.backgroundColor = .yellow
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
PlaygroundPage.current.needsIndefiniteExecution = true
堆栈视图的属性是什么?每次都一样大小?因为您没有为按钮设置框架。@Larme stackview应该包含所需的按钮数量,我尝试为按钮设置框架,让button=UIButton(框架:CGRect(x:145,y:32,宽度:64,高度:64)),但stackview中没有按钮2问题,您的
self
是否有可能变成nil
?您是否为stackView
设置了任何帧/约束。我刚刚将您的代码粘贴到一个游乐场,并为stackView
设置了约束,它就可以工作了。
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
self.view = view
let stackView = UIStackView()
for item in 1...5 {
let button = UIButton()
button.setTitle("Button \(item)", for: .normal)
button.backgroundColor = .red
stackView.addArrangedSubview(button)
}
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.backgroundColor = .yellow
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
PlaygroundPage.current.needsIndefiniteExecution = true