【问题标题】:How can I reinitialize a UITableViewCell in Swift?如何在 Swift 中重新初始化 UITableViewCell?
【发布时间】:2021-08-02 04:33:09
【问题描述】:

我正在使用 UITableViewCell 来显示数据。当视图加载时,数据是空的,但是一旦 api 调用完成,我想重新初始化 UITableViewCell 以便数据可以出现。我正在使用以下代码,但TableView.reloadData() 不会重新初始化 UITableViewCell,因此不会重新加载数据。

TableViewCell

class TableViewCell: UITableViewCell {
    
    var Info: Information?
    let Chart = LineChartView(frame: .zero)
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        print("initialized")
        self.contentView.addSubview(Chart)
        Chart.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            Chart.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 10),
            Chart.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -10),
            Chart.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -10),
            Chart.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 10),
        ])
        let data = ChartHelpers().makeLineChart(data: Info?.Values ?? [Double]())
        Chart.data = data
        self.contentView.layoutIfNeeded()
     }

     required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
    }
}

视图控制器


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var Info: Information?
    let TableView = UITableView(frame: .zero)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        APICall()
        setUpUI()
    }

    func setUpUI() {
        view.addSubview(TableView)
        TableView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            TableView.topAnchor.constraint(equalTo: view.topAnchor),
            TableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            TableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            TableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        ])
        self.TableView.register(TableViewCell.self, forCellReuseIdentifier: "Chart")
        TableView.delegate = self
        TableView.dataSource = self
        TableView.reloadData()
        view.layoutIfNeeded()
    }

    func APICall() {
        API().fetchInformation(Name: "John Doe") { (Info) in
            //success connecting to api
            DispatchQueue.main.async {
                self.Info = Info
                self.TableView.reloadData()
            }
        } failure: { (error) in
            //failure connecting to api

            }
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = TableView.dequeueReusableCell(withIdentifier: "Chart", for: indexPath) as! TableViewCell
        tableView.rowHeight = 300
        cell.Info = self.Info
        return cell
    }
}

【问题讨论】:

    标签: ios swift api uitableview reloaddata


    【解决方案1】:

    didSet 添加到您的Info 变量以触发构建图表。

    var Info: Information? {
       didSet {
         let data = ChartHelpers().makeLineChart(data: Info?.Values ?? [Double]())
         Chart.data = data
         self.contentView.layoutIfNeeded()
       }
    }
    

    在初始化期间不会触发 didSet 观察者,因此当您在 API 调用后有有效数据时重新加载单元格时,您需要再次调用序列。

    【讨论】:

      【解决方案2】:

      最好不要在 init 中进行配置,因为 cell 实例可能会被重用。应在使单元出队时完成设置。这可以通过设置方法或通过设置属性来完成,就像您在此处使用 Info 所做的那样(顺便说一下,将其命名为 info 会更快捷)。

      在此处获得所需内容的最简单方法是将didSet 添加到您的Info 属性并在那里调用设置方法:

      var info: Information? {
          didSet {
              let data = ChartHelpers().makeLineChart(data: Info?.Values ?? [Double]())
              Chart.data = data
              self.contentView.layoutIfNeeded()
          }
      }
      
      

      尽管从长远来看,其他重构可能会更好。

      【讨论】:

      • 谢谢你,这很完美!您能否简要解释一下这是如何工作的?
      • 是的!这是一个属性观察器,可用于挂钩存储属性(因此不是计算变量)上的此类事件。更多信息可以在这里找到:docs.swift.org/swift-book/LanguageGuide/Properties.html
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 2021-01-22
      • 2016-06-26
      相关资源
      最近更新 更多