如何修复viewDIdLoad中的indexPath错误?

时间:2018-07-05 08:17:53

标签: swift sorting struct viewdidload indexpath

我对indexPath.row有疑问。在cellForRowAt内部,这些行很完美:

let cell = tableView.dequeueReusableCell(withIdentifier: "MenuViewCell", for: indexPath) as! MenuViewCell

        let item = converters[indexPath.row]
        cell.ConverterName.text = item.converterName
        cell.converterImage.image = item.converterImg

但是当我尝试在viewdidload中实现它时,出现了一个错误: “使用未解析的标识符'indexPath'”

和代码:

struct converter {
        let converterName: String
        let converterImg: UIImage
    }

var converters = [converter(converterName: "Converter of time", converterImg: #imageLiteral(resourceName: "time")),
                  converter(converterName: "Converter of pressure", converterImg: #imageLiteral(resourceName: "davlenie")),
                  converter(converterName: "Converter of speed", converterImg: #imageLiteral(resourceName: "skorost")),
                  converter(converterName: "Converter of distance", converterImg: #imageLiteral(resourceName: "dlinna"))]



override func viewDidLoad() {
    super.viewDidLoad()

    let item = converters[indexPath.row]
    let itemSort = item.converterName
    self.converters = itemSort.sorted { $0 < $1 }
    self.tableView.reloadData()

}

1 个答案:

答案 0 :(得分:0)

viewDidLoad没有像cellForRowAt那样传递IndexPath参数。

IndexPath用于标识要构建或选择的当前单元格。在viewDidLoad中不需要它。数组中有4个转换器,只要需要,就可以通过使用其索引来选择任意转换器。