Reputation: 6092
I created a tableViewController programmatically like so :
import UIKit
class ViewController: UIViewController {
private var tableView: UITableView!
var elements = [1, 2, 3, 4, 5].map { "Elément \($0)" }
// MARK: - View controller life cycle
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: .zero, style: .grouped)
tableView.dataSource = self
tableView.delegate = self
view.addSubview(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "BasicTableViewCell")
// Pin tableView to view
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let element = elements[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "BasicTableViewCell")!
cell.textLabel?.text = element
cell.accessoryType = .disclosureIndicator
return cell
}
}
extension ViewController: UITableViewDelegate { }
This is the storyboard, mostly empty:
This gives a strange cell inset on the leading and trailing side :
What is really weird is: if I create an empty tableView in the storyboard (instead of adding it the the view programmatically), then everything is fine!
This is what the storyboard becomes, with an iBOutlet to the tableView.
This is the class now (I didn't include the extensions, they are unchanged)
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var elements = [1, 2, 3, 4, 5].map { "Elément \($0)" }
// MARK: - View controller life cycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "BasicTableViewCell")
}
}
I can't believe there would be no way to create the tableView completely programmatically without this bug. Did I miss a parameter on the tableView ?
Upvotes: 0
Views: 317
Reputation: 6693
It's because of cellLayoutMarginsFollowReadableWidth
. Just add it to your setup code.
tableView.cellLayoutMarginsFollowReadableWidth = false
Upvotes: 2