Search code examples
swiftuitableviewuinavigationcontroller

swift: after adding navigationController to viewController, tableView height is not fitting screen


after adding this codes to appDelegate inside didFinishLaunchingWithOptions function:

self.window = UIWindow(frame: UIScreen.main.bounds)
let mainView = PageViewController(coder: NSCoder()) 
let nav1 = UINavigationController(rootViewController: mainView!)
nav1.navigationBar.isTranslucent = false
self.window!.rootViewController = nav1
self.window?.makeKeyAndVisible()

tableView height is not looking good, some part of tableView(cells) not fitting screen

my codes for implementing tableView:

let myTableView = UITableView(frame: CGRect(x: 0, y: 40, width: screenSize.width, height: screenSize.height-40))
myTableView.bounces = false
myTableView.tableFooterView = UIView()
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
myTableView.register(MyTableViewCell.self, forCellReuseIdentifier: "cellID2")
myTableView.dataSource = self
myTableView.delegate = self

for show all part of tableView in screen i have to change the first line above code to this:

let myTableView = UITableView(frame: CGRect(x: 0, y: 40, width: screenSize.width, height: screenSize.height-90))

why this is happening and what should i do to solve this problem thanks


Solution

  • Try something like this but don't forget to add myTableView as a subview before you set anchors:

                myTableView.translatesAutoresizingMaskIntoConstraints = false
                myTableView.leftAnchor.constraint(equalTo: myTableView.superview!.leftAnchor).isActive = true
                myTableView.rightAnchor.constraint(equalTo: myTableView.superview!.rightAnchor).isActive = true
                myTableView.topAnchor.constraint(equalTo: myTableView.superview!.topAnchor).isActive = true
                myTableView.bottomAnchor.constraint(equalTo: myTableView.superview!.bottomAnchor).isActive = true