Usmaan Mahmood
Usmaan Mahmood

Reputation: 53

How to add multiple subviews in xcode in a viewcontroller

I have a view controller when practicing making a newsfeed following a youtube tutorial but in order to do so I had to include a sub view:

        view.addSubview(tableView)

It is intended to act like a table view where I can scroll through posts. However, I want to add an "add posts" button but only problem is that it does not show up on the simulator because as you can see I needed to put a subview in so I think the button is behind tableView. Is there a way that I can bring it forward.

I am still learning so please be patient with me :).

Upvotes: 1

Views: 1524

Answers (2)

Rupesh
Rupesh

Reputation: 141

Even though as sahib mentioned self.view.bringSubviewToFront(yourButton) solves the issue. I assume it won't make a good User Experience.

Instead I suggest you to keep the button as tableHeader or footerView as per your need. Or you can set the button frame to the top of viewController and set the tableview's frame below it as follows:

let viewWidth = self.view.frame.width
let viewHeight = self.view.frame.height
let button = UIButton(frame: CGRect(x: viewWidth - 60,y:20,height:30,width: 40))
self.view.addSubView(button)
let tableView = UITableView(frame: CGRect(x: viewWidth, y: viewHeight-50,height:viewHeight-50,width:viewWidth))
self.view.addSubView(tableView)

You can achieve the same using constraints too.

Upvotes: 0

sahib
sahib

Reputation: 85

if you are sure you that your button is behind your tableView, then you can use this code

self.view.bringSubviewToFront(yourButton)

Upvotes: 1

Related Questions