Как использовать dequeueReusableCellWithIdentifier в Swift?
Если я раскомментирую
tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?)
Я получаю сообщение об ошибке в строке
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
который говорит UITableView? does not have a member named 'dequeueReusableCellWithIdentifier'
Если я разворачиваю табличное представление, ошибка исчезает, но в Objective-C мы обычно проверяем, существует или нет ячейка, а если нет, мы создаем новую. В Swift, поскольку в поставляемом шаблоне используется ключевое слово let
и разворачивается необязательно, мы не можем переназначить его, если он равен нулю.
Каков правильный способ использования dequeueReusableCellWithIdentifier в Swift?
Ответы
Ответ 1
Вы можете неявно разворачивать параметры для метода, а также приводить результат dequeueReusableCellWithIdentifier
, чтобы дать следующий краткий код:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
//configure your cell
return cell
}
Ответ 2
Если тип ячейки не был зарегистрирован в представлении таблицы перед загрузкой таблицы, вы можете использовать следующее для извлечения экземпляра ячейки:
private let cellReuseIdentifier: String = "yourCellReuseIdentifier"
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier)
if (cell == nil) {
cell = UITableViewCell(style:UITableViewCellStyle.Subtitle, reuseIdentifier:cellReuseIdentifier)
}
cell!.textLabel!.text = "Hello World"
return cell!
}
Ответ 3
Вам нужно развернуть переменную tableView, поскольку она является необязательной
if let realTableView = tableView {
let cell = realTableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// etc
} else {
// tableView was nil
}
или вы можете сократить его на
tableView?.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
В ответ на ваш вопрос о 'in Objective-C мы обычно проверяем, существует или нет ячейка, а если нет, мы создаем новую', dequeueReusableCellWithIdentifier
всегда возвращает ячейку (если вы " я зарегистрировал класс или нить для этого идентификатора), поэтому вам не нужно создавать новый.
Ответ 4
версия swift 3:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath!) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"CellIdentifier", for: indexPath) as UITableViewCell
return cell
}
Ответ 5
В версиях Swift 3 и Swift 4 вы просто используете этот
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath as IndexPath) as UITableViewCell
cell.textLabel?.text = "cell number \(indexPath.row)."
//cell code here
return cell
}
В версии Swift 2
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = "cell number \(indexPath.row)."
//cell code here
return cell
}