Frederik Hensen
Frederik Hensen

Reputation: 23

How do I create dynamic views in swift?

I am making an IOS app where the main layout is a UITableView, and cells are completely dynamic and loaded from server. Each tableview item is a different layout.

For example, lets take first item of the tableview:

Server tells it should have a label, 2 buttons and a textbox, it should be created by code. I figured out how to create those elements themselves, the problem is how do I position them?

Ideally I would like to add each layout item under the previous one. And tableviewcell should wrap those, grow or collapse according to views.

I am fairly new to IOS/Swift. Is there any way to implment this easily? In android I just used a linearlayout and added views one by one. Does IOS have something like that? Or do I have to manually set heights, widths, and coordinates of all items?

Thanks in advance.

Here is some code:

if let Actions = AppData["Forms"][0]["AvailableActions"].array{
                for var i = 0 ; i < Actions.count ; ++i {
                    if Actions[i].int == 1{
                        let actionButton1 = UIButton(frame: CGRectMake(0, 0, 96, 30))
                        actionButton1.setTitle("View", forState: .Normal)
                        actionButton1.setTitleColor(UIColor.redColor(), forState: .Normal)
                        cell.actionsLayout.addSubview(actionButton1)
                    }
                }
            }

Upvotes: 2

Views: 3616

Answers (1)

Ajay Kumar
Ajay Kumar

Reputation: 1827

You can do with self-sizing cells, in this case you just need to

  1. Give proper constraints to your table view cell subviews,(i.e all your subviews should be connected to each other and topmost subview should have top-space constraints and bottommost subview should have bottom-space constraints).

    1. Specify the estimatedRowHeight of your table view.

    2. Set the rowHeight of your table view to UITableViewAutomaticDimension

For step 2-3 steps mentioned above,just add following code in your viewDidLoad -

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension

For understanding of self-sizing cells you can follow this link http://www.appcoda.com/self-sizing-cells/

Upvotes: 1

Related Questions