Reputation: 43
I have as simple setup where I have a view controller embedded in a UINavigationController
. On this view controller, I want to display multiple tableView
s next to each other (horizontally). I am creating and adding the tableView
s in viewDidLoad
. It works well except that there is an issue with the y
-position of every tableView
except for the first one.
When creating the tableView
s programmatically, the first tableView
is always properly displayed right below the UINavigationBar
. However all of the others are displayed "behind" the UINavigationBar
even though the y
-coordinate is equal to 0
in all of the tableView
s.
This is what it looks like when you run it on the simulator (note that the tableView
itself has a green backgroundColor
):
And this is the code for it:
class ViewController: UIViewController {
var tableViews: [UITableView] = [] // maintained only for debugging purposes
override func viewDidLoad() {
super.viewDidLoad()
let tableViewCount: Int = 5
createTableViews(tableViewCount)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
print(#function, tableViews)
}
func createTableView(count: Int) {
let width = Int(self.view.bounds.width)/count
for i in 0..<count {
let x = width * i
let y = 0
let height = Int(view.bounds.height)
let frame = CGRect(x: x, y: y , width: width, height: height)
let tableView = UITableView(frame: frame, style: UITableViewStyle.Plain)
tableView.backgroundColor = .greenColor()
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
view.addSubview(tableView)
tableView.tag = i
tableViews.append(tableView)
}
}
}
I am only maintaining the tableViews
property so that I can print them in viewDidAppear
. The console output in viewDidAppear
shows that all my tableView
s have the same y
position on their frames (= 0
).
I did find an easy (yet hacky) fix for this. All I have to do is set the first y
to 0
and the rest to 64
(which is the height of the status bar plus the height of the navigation bar). Like so:
let y = i == 0 ? 0 : 64
Does anyone have an idea why the tableView
s are being misplaced? According to my understanding, all tableView
s should be displayed right below the navigation bar, as this is the vertical origin of the view controller's view
?
Upvotes: 1
Views: 202
Reputation: 7361
According to my understanding, all tableViews should be displayed right below the navigation bar, as this is the vertical origin of the view controller's view?
This is only the case in my experience if you set myNavigationController.navigationBar.translucent = false
. If the navigation bar is translucent, the top of your view is still the top of the screen.
On a side note, you should definitely look into laying these views out via auto layout, rather than this hacky frame math. Would simplify your code a lot.
Upvotes: 1