首页 > 解决方案 > 设备方向更改时 ULTextField 值消失

问题描述

我使用 Xibs 在 UITableViewController 中加载单元格,并且由于某种原因,一旦设备方向发生变化,单元格就会重新加载,并且所有输入的 UITextField 值都会消失。有没有办法防止这种情况或更好的方法来解决这个价值消失的问题。

我的单元格如下

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = configCellView(index: indexPath.row) as? UITableViewCell

    cell?.selectionStyle = .none
    return cell ?? UITableViewCell()
}

我的 configCellView 方法如下

   private func configCellView(index: Int) -> UIView? {
    switch formType {
    //This LOG form works fine even device orientation changes 
    case .LOG:
        if let cell = getXibFile(cellType: LogFormTableViewCell.self, cellIdenifier: Constants.LOGFORM_CELL_IDENTIFIER) {
        
        return cell

        }

  //This is where the issue is 
    case .PROSPECT:
        switch index {
            case 0:
                let cell = getXibFile(cellType: LogFormTableViewCell.self, cellIdenifier: Constants.LOGFORM_CELL_IDENTIFIER)

                return cell
            default:
               
               
                    if let cell = getXibFile(cellType: ContactFormTableViewCell.self, cellIdenifier: Constants.CONTACTFORM_CELL_IDENTIFIER){
                                                 
                  
                     return cell
                
                    }
        }

     }



 func getXibFile<T: UITableViewCell>(cellType: T.Type, cellIdenifier: String) -> T? {
    return Bundle.main.loadNibNamed(cellIdenifier, owner: self, options: nil)?.first as? T
 }

标签: swiftuitableviewxibswift5

解决方案


您当前正在做的是每次不推荐重新加载 tableView 时创建一个新单元格。您必须dequeueReusableCell(withIdentifier:)这样才能重用单元格,这在内存方面更有效。

关于数据,您可能希望每次cellForRow调用时都有一个数组来存储和检索数据。


推荐阅读