Reputation: 119
I am trying to create buttons after getting response from a network request. How do I do this and position them after creating them, after the view is loaded. I am also creating my views programmatically and using 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)
}
Upvotes: 0
Views: 988
Reputation: 1264
/// 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)
}
Where it says // Constrain your button here!
- if you want multiple buttons in a row or column, I'd recommend using a UIStackView, and adding them as ArrangedSubviews, for example.
Upvotes: 1
Reputation: 86
Try adding your buttons to an override of viewWillAppear()
https://developer.apple.com/documentation/uikit/uiviewcontroller/1621510-viewwillappear
Or this older posting might help you out:
How to create a button programmatically?
But I would try using viewWillAppear() first
Upvotes: 0