【问题标题】:Reloading UITableView and running something afterwards [duplicate]重新加载 UITableView 并在之后运行一些东西 [重复]
【发布时间】:2018-02-21 11:08:14
【问题描述】:

我在重新加载 tableView 时遇到问题,这是我拥有的那批代码:

func updateIncomingData () {

        print ("Received String:")
        print (receivedDataString)
        print("Clearing TNU Array")
        TNUArray.removeAll()
        temperatureReadingArray = receivedDataString.components(separatedBy: " ")
        print("temperatureReadingArray is:")
        print(temperatureReadingArray)
        self.temperatureReadingsTable.reloadData()
        calculateTNU()
    }
func calculateTNU()
    {
        var TNU: Double = 0.000
        print("TNU Array:")
        print(TNUArray)
        let minValue = TNUArray.min()
        print("Values MIN/MAX are:")
        print(minValue ?? "nil")
        let maxValue = TNUArray.max()
        print(maxValue ?? "nil")
        if (minValue != nil && maxValue != nil)
        {
            TNU = maxValue! - minValue!
            calculatedTNU = String(format:"%.3f", TNU)
            TNULabel.text = calculatedTNU
        }
        else
        {
            print("Max or Min had nil values")
        }  
    }

现在,您可以看到我在调用 calculateTNU() 之前调用了 reloadData()。这会调用表加载函数,对此特别感兴趣:

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

        let cell = tableView.dequeueReusableCell(withIdentifier: temperatureReading) as! TemperatureReading

        cell.channelLabel.text = channelNames[indexPath.row]
        cell.readingLabel.text = temperatureReadingArray[indexPath.row]

        if (channelNames.count == 1)
        {
         cell.toggleSwitch.isHidden = true
        }
        if (cell.toggleSwitch.isOn)
        {
            if let value = Double(cell.readingLabel.text!)
            {
                print("valid number, appending")
                TNUArray.append(value)
            }
            else
            {
                print("Not a valid number reading")
            }
        }
        return cell
    }

现在,问题是它在完成重新加载数据之前运行了 calculateTNU(),这导致我的 calculateTNU() 函数没有任何值可供读取(因为在填充表时它也会填充所需的数组用于 TNU 计算)。

在执行下一个命令函数之前是否有“等到它重新加载”?

【问题讨论】:

  • 您不应该从cellForRow(at:) 内部操作您的数据数组。这个函数的调用顺序没有定义,随着table view的滚动会被多次调用。

标签: ios swift uitableview


【解决方案1】:

通常最好的策略是避免这种情况。您可以在其他地方调用TNUArray.append - 也许当temperatureReadingArray 内容更改或toggleSwitch 状态更改时。

tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 是用来填满你的单元格的,你不应该在那里做任何无关的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多