0

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)

}
Samuel Kith
  • 109
  • 12
  • I recommend that you create the button and put it on the main view in `viewDidLoad` and just hide/show it at the right time. That's much easier. – Daniel T. Jun 06 '19 at 00:55
  • The problem is I do not know how many buttons I need to create until the response comes back. – Samuel Kith Jun 06 '19 at 04:39

2 Answers2

1
/// 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.

jake
  • 1,226
  • 8
  • 14
0

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