[英]How do I create/add UIView after viewDidLoad?
我試圖在收到網絡請求的響應后創建按鈕。 在加載視圖后,如何在創建它們之后進行定位。 我還以編程方式創建我的視圖並使用AutoLayout。
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)
}
嘗試將按鈕添加到viewWillAppear()的覆蓋
https://developer.apple.com/documentation/uikit/uiviewcontroller/1621510-viewwillappear
或者這個較舊的帖子可能會幫助你:
但我會首先嘗試使用viewWillAppear()
/// 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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.