我试图在收到网络请求的响应后创建按钮。如何执行此操作并在创建它们之后、加载 View 之后定位它们。我还以编程方式创建 View 并使用自动布局。
CustomView.swift
class CustomView: UIView {
override init(frame: CGRect) {
super.init(frame: UIScreen.main.bounds)
backgroundColor = .red
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
ViewController.swift
// Load custom view
override func loadView() {
view = CustomView()
}
override func viewDidLoad() {
super.viewDidLoad()
// Create buttons after getting response
viewModel.output.apiOutput
.subscribe(onNext: { posts in
for post in posts {
// create buttons
}
})
.dispose(by: disposeBag)
}
最佳答案
/// Helper function to create a new button.
func createButton(_ title: String) -> UIButton {
let button = UIButton()
button.backgroundColor = .blue
button.setTitle(title, .normal)
// Add the button as a subview.
self.view.addSubview(button)
}
override func viewDidLoad() {
super.viewDidLoad()
// Just set the viewController's view to your custom view here.
self.view = CustomView()
// Create buttons after getting response
viewModel.output.apiOutput
.subscribe(onNext: { posts in
for post in posts {
// Create a button. Change "title" to the title of your post, etc.
let button = createButton("Title")
// Constrain your button here!
}
})
.dispose(by: disposeBag)
}
上面写着 //在此处约束您的按钮!
- 如果您想要在行或列中放置多个按钮,我建议使用 UIStackView,并将它们添加为 ArrangedSubviews,例如。
关于ios - viewDidLoad 之后如何创建/添加 UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56465693/