Поток 1: Exc Bad Instruction в UITableViewCell - PullRequest
0 голосов
/ 13 декабря 2018

С кодом ниже, я хочу напечатать имя и цену в каждой ячейке таблицы.Сборка выполняется без проблем, но когда я запускаю приложение, в var item1 = arrData[i]["name"]

появляется сообщение об ошибке Bad Instruction. Вот полный код:

class ViewController3: UIViewController, UITableViewDelegate, 
UITableViewDataSource {

let arrData: [[String:Any]] = [
    ["name": "spiderman", "price": 5000],
    ["name": "superman", "price": 15000],
    ["name": "batman", "price": 3000],
    ["name": "wonder woman", "price": 25000],
    ["name": "gundala", "price": 15000],
]

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrData.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let identifier = "Cell"

    var cell = tableView.dequeueReusableCell(withIdentifier: identifier)

    var i = 0

    while i <= arrData.count {
        var item1 = arrData[i]["name"]
        var item2 = arrData[i]["price"]
        cell?.textLabel?.text = "\(item1) \(item2)"
        i = i + 1
    }
    return cell!

}

}

Ответы [ 4 ]

0 голосов
/ 13 декабря 2018

Вместо цикла while используйте indexPath.row, чтобы отображать правильные данные в каждой строке в UITableView.И используйте многоразовые ячейки, как показано ниже:

let identifier = "Cell"

override func viewDidLoad() {
    super.viewDidLoad()

    tableview.register(UITableViewCell.self, forCellReuseIdentifier: identifier)
    tableview.reloadData()
}

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

    let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)

    let item1 = arrData[indexPath.row]["name"]
    let item2 = arrData[indexPath.row]["price"]
    cell.textLabel?.text = "\(item1!) \(item2!)"

    return cell
}
0 голосов
/ 13 декабря 2018

Когда вы используете инструкцию i <= arrData.count для 5-го индекса, вы получите сбой.Вы должны изменить или лучше использовать в инструкции </p>

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "Cell"

var cell = tableView.dequeueReusableCell(withIdentifier: identifier)

var i = 0

while i < arrData.count {
    var item1 = arrData[i]["name"]
    var item2 = arrData[i]["price"]
    cell?.textLabel?.text = "\(item1) \(item2)"
    i = i + 1
}
return cell!

}

0 голосов
/ 13 декабря 2018

Индекс массива начинается с нуля.Это означает, что первый элемент не arrData[1], а arrData[0].поэтому while i <= arrData.count вызовет выход за пределы массива.

Попробуйте while i < arrData.count

PS, коды в tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) подключены, почему вы добавляете цикл while?все ячейки таблицы будут выглядеть одинаково.

0 голосов
/ 13 декабря 2018

Исправить этот кусок while i < arrData.count.Индекс выходит за пределы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...