Reputation: 472
In iOS 14 TableView with textField is not working. Is someone have solution ?
Here is sample code:
class TestController: UIViewController {
let tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
view.addSubview(tableView)
tableView.edgesToSuperview()
tableView.backgroundColor = .gray
tableView.register(TestCell.self, forCellReuseIdentifier: TestCell.reuseID)
tableView.dataSource = self
}
}
extension TestController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TestCell.reuseID, for: indexPath)
return cell
}
}
class TestCell: UITableViewCell {
let textField = UITextField()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .red
addSubview(textField)
textField.height(50)
textField.backgroundColor = .blue
textField.edgesToSuperview()
selectionStyle = .none
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The same code works on iOS 13 but is not working on iOS 14. Is someone fixed this issue ? (Xcode Version 12.0 (12A7209))
Upvotes: 6
Views: 2305
Reputation: 3804
In iOS 14 the UITableViewCellContentView hierarchy is different.
In tableView(_:cellForRowAt:), instead of doing something like this:
cell.addSubview(textField)
Change it to:
cell.contentView.addSubview(textField)
Upvotes: 2
Reputation: 622
You should not use directly addSubview in a cell but instead add it inside the ContentView:
contentView.addSubview(textField)
This should work and solve your problem
Upvotes: 20