Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios 14 Tableview cell with textField not working

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))

like image 761
Islom Alimov Avatar asked Dec 05 '22 08:12

Islom Alimov


1 Answers

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

like image 191
Kevin Vacquier Avatar answered Jan 08 '23 03:01

Kevin Vacquier