【问题标题】:ios 14 Tableview cell with textField not working带有textField的ios 14 Tableview单元格不起作用
【发布时间】:2021-01-07 06:25:29
【问题描述】:

在带有 textField 的 iOS 14 TableView 中不起作用。有人有解决方案吗?

这里是示例代码:

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

相同的代码适用于 iOS 13,但不适用于 iOS 14。有人解决了这个问题吗? (Xcode 版本 12.0 (12A7209))

【问题讨论】:

    标签: uitableview uikit uitextfield ios14


    【解决方案1】:

    您不应该在单元格中直接使用 addSubview,而是将其添加到 ContentView 中:

    contentView.addSubview(textField)
    

    这应该可以解决您的问题

    【讨论】:

      【解决方案2】:

      在 iOS 14 中,UITableViewCellContentView 层次结构有所不同。

      在 tableView(_:cellForRowAt:) 中,而不是这样做:

      cell.addSubview(textField)
      

      改成:

       cell.contentView.addSubview(textField)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-18
        • 1970-01-01
        • 2019-11-09
        • 2019-09-02
        • 1970-01-01
        相关资源
        最近更新 更多