Reputation: 4339
How can I add controls dynamically in view.
I read data from REST API, and then I need to add checkbox controls to view, after datepicker.
Example:
[
{
"id": 1,
"name": "White",
"branch_type": 2
},
{
"id": 2,
"name": "Black",
"branch_type": 2
}
]
and I get that with Alamofire and SwiftyJSON, now I need to append that White
and Black
as checkboxes to this view.
Do I need some container or something?
Any example for this?
Upvotes: 0
Views: 829
Reputation: 4951
Use a UIStackView. It enables you to easily add/remove controls to your form dynamically.
1) Create a Stack view
In Interface Builder, select your date picker then click on the stack view icon. This will create a new stack view and place your date picker inside. Tweak the stack view attributes like spacing to specify spacing between your controls, and make sure the Axis is set to vertical.
2) Add IBOutlet
Next go to your controller file and create an IBOutlet for your stack view so you can refer to it from code. Make sure you connect it to the stack view you just created in Interface Builder.
@IBOutlet weak var myStackView: UIStackView!
3) Add Controls
Once you have retrieved your remote data and have parsed it out into an array, run it through a for loop. For each data item you should create your control (check box, text field, whatever you need) and add it to the stack view:
//...
myStackView.addArrangedSubview(myControl)
The stack view will manage the positioning of the added controls in such a way that you can easily add or remove views on the fly.
Upvotes: 2