Понимание Xcode UITableViewCell - PullRequest
0 голосов
/ 02 мая 2019

Я определил класс с именем c1 для ячейки-прототипа следующим образом:

enter image description here

enter image description here

Я определил код для c1 следующим образом:

 class c1 : UITableViewCell {

    public func configure(indexPath: IndexPath) -> UITableViewCell {
        let place = places[indexPath.row]
        self.textLabel?.text = place.name
        self.detailTextLabel?.text = "\(place.timestamp)"
        return self
    }
}

Внутри UITableViewController следующий код:

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

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

    // Configure the cell...
    return cell.configure(indexPath);
}

Но это работает не потому, что обв. компилятор не знает о c1: «Значение типа 'UITableViewCell' не имеет члена 'configure'"

И я не понимаю, почему: если я укажу имя класса «c1» в раскадровке, я ожидал, что XCODE инстанцирует появление. Класс автоматически для механизма повторного использования. Таким образом, метод tableView должен возвращать экземпляр класса «c1» во время выполнения, который является потомком UITableViewCell, чтобы иметь доступ к методу «configure»?

Ответы [ 4 ]

0 голосов
/ 02 мая 2019

Чтобы получить доступ к методам вашего UITableViewCell, вам придется привести ячейку к этому конкретному UITableViewCell

т.е.

let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_IDENTIFIER") as? YOUR_CELL_CLASS

В случае еслиу вас есть кратное число UITableViewCell, поэтому вы должны назначить другой идентификатор, исходя из того, что вы можете идентифицировать конкретную ячейку.Более или менее должна быть осведомленность, которая отображает вашу ячейку на основе ваших данных.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let aCellType = aCellData[indexPath.row].cellType //aCellData is the predefined data
    switch aCellType {

    case c1:
        let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_IDENTIFIER") as? YOUR_CELL_CLASS_C1
        cell.YOUR_METHOD_OF_THIS_CELL()
        return cell

    case c2:
        let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_IDENTIFIER") as? YOUR_CELL_CLASS_C2
        cell.YOUR_METHOD_OF_THIS_CELL()
        return cell

    case c3:
        let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_IDENTIFIER") as? YOUR_CELL_CLASS_C2
        cell.YOUR_METHOD_OF_THIS_CELL()
        return cell

    default:

        debugPrint("That's all folks")
    }

    return UITableViewCell()
}

Надеюсь, это поможет вам!

0 голосов
/ 02 мая 2019

Должен использовать тип UITableview ячейка

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath) as? c1    // to inherit the method of class c1, need to cast
    // Configure the cell...
    return cell.configure(indexPath);
}
0 голосов
/ 02 мая 2019

Пожалуйста ⌥-нажмите на dequeueReusableCell или прочитайте документацию

func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell

возвращает базовый класс UITableViewCell

Если вы объявляете пользовательский (под) класс, вы должны привести ячейку к подклассу. Кстати, назовите класс начальной заглавной буквой.

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

А в configure вам, возможно, придется вернуть Self или c1

public func configure(indexPath: IndexPath) -> Self {
    let place = places[indexPath.row]
    self.textLabel?.text = place.name
    self.detailTextLabel?.text = "\(place.timestamp)"
    return self
}

А откуда в клетке places? Метод configure кажется бессмысленным.

0 голосов
/ 02 мая 2019

просто приведите ячейку к вашей конкретной ячейке

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath) as? c1

и работа сделана

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