从网络请求获得响应后,我试图创建按钮。在创建视图后,在加载视图后,我该如何做并放置它们。我也在以编程方式并使用AutoLayout创建视图。
CustomView.swift
git clone
ViewController.swift
git
答案 0 :(得分:0)
尝试将按钮添加到替代viewWillAppear()
https://developer.apple.com/documentation/uikit/uiviewcontroller/1621510-viewwillappear
或者该较早的帖子可能会帮助您:
How to create a button programmatically?
但是我会先尝试使用viewWillAppear()
答案 1 :(得分:0)
/// 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)
}
上面写着// Constrain your button here!
的地方-如果要在一行或一列中使用多个按钮,我建议您使用UIStackView,然后将其添加为ArrangedSubviews。