Множественная реализация пользовательских uitableviewcell с использованием динамических ячеек прототипа

#ios #swift #uitableview

#iOS #swift #uitableview

Вопрос:

В моем проекте используются три разных динамических прототипа tableviewcells.

Две из них являются стандартными ячейками (базовыми с различными опциями), а одна — пользовательская ячейка. И это может изменяться по мере необходимости.

Проблема, с которой я сталкиваюсь, заключается в удалении ячеек из очереди.

Если они выполняются обычно как UITableViewCells, я не могу использовать свои пользовательские ячейки или действия.

 let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
  

И, если они выполняются другим способом, приложение завершает работу с приведенной ниже ошибкой.

 let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SwitchTableViewCell
  

Ошибка:

 Could not cast value of type 'UITableViewCell' (0x38595c58) to 'AppName.SwitchTableViewCell' (0x13cdf8).
  

Ниже приведена реализация cellForRowAtIndexPath метода,

 // MARK: - UITableViewDelegate Methods

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // Setup a cellIdentifer string to store the cell reuse identifier you want to use for each row.
    var cellIdentifier: String

    // Switch through each row and set the appropriate cell reuse identifier
    switch sections[indexPath.section].items[indexPath.row] {
    case .AudioDevices, .Acknowledgments:
        cellIdentifier = "DisclosureCell"
    case .AllowNotifications, .ShowCloudMusic:
        cellIdentifier = "SwitchCell"
    case .Version:
        cellIdentifier = "RightDetailCell"
    }

    // Populate your cell reuse identifier into the cell

    if cellIdentifier == "SwitchCell" {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SwitchTableViewCell
        return cell
    } else {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
        return cell
    }

    // Switch through each cell, and implement the labels/setup for each row
    // The order of the cases is irrelevant!
    switch sections[indexPath.section].items[indexPath.row] {
    case .AudioDevices:
        cell.textLabel?.text = "Audio Devices"
        cell.detailTextLabel?.text = String(userDefaults.integerForKey(audioDeviceListKey))
    case .AllowNotifications:
        cell.switchCellLabel?.text = "Allow Notifications"
        cell.userInteractionEnabled = false
    case .ShowCloudMusic:
        cell.switchCellLabel?.text = "Show Cloud Music"
    case .Acknowledgments:
        cell.textLabel?.text = "Acknowledgements"
        cell.detailTextLabel?.text = ""
    case .Version:
        cell.textLabel?.text = "Version"
        cell.detailTextLabel?.text = buildVersion
        cell.detailTextLabel?.textColor = UIColor.lightGrayColor()
        cell.userInteractionEnabled = false
    }
    // Return the cell
    return cell
}
  

Скриншот:

Изображение

Комментарии:

1. «Два или один», что это значит?

2. Извините за опечатку, две из них являются базовыми ячейками с небольшими изменениями, а другая — пользовательская..

3. вы зарегистрировали свою пользовательскую ячейку? TableView.RegisterClass(CustomCell.self, forCellReuseIdentifier: «Ячейка»)

4. Извините, я не понял вашего вопроса, пожалуйста, уточните это, загрузите снимок экрана вашего экрана в свой вопрос, чтобы мы легко поняли ваш вопрос..

5. покажите свой полный cellForRowAtI...... код

Ответ №1:

Используйте разделитель по умолчанию.

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

 func tableView cellForRowAtInd....... {
    //depends on what base you separate both cells 
    if condition = true { 
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SwitchTableViewCell
        return cell
    } else {
        let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
       return cell
    }

}
  

Обновление на основе вашего cellForRowAtIndexPath кода:

Вы уже возвращаетесь к ячейке перед запуском другой части кода. Следовательно, ячейка уже возвращена и бесполезна для другой части кода.

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // Setup a cellIdentifer string to store the cell reuse identifier you want to use for each row.
    var cellIdentifier: String

    // Switch through each row and set the appropriate cell reuse identifier
    switch sections[indexPath.section].items[indexPath.row] {
    case .AudioDevices, .Acknowledgments:
        cellIdentifier = "DisclosureCell"
    case .AllowNotifications, .ShowCloudMusic:
        cellIdentifier = "SwitchCell"
    case .Version:
        cellIdentifier = "RightDetailCell"
    }

    // Populate your cell reuse identifier into the cell

    if cellIdentifier == "SwitchCell" {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SwitchTableViewCell

        // Switch through each cell, and implement the labels/setup for each row
        // The order of the cases is irrelevant!
        switch sections[indexPath.section].items[indexPath.row] {
        case .AudioDevices:
            cell.textLabel?.text = "Audio Devices"
            cell.detailTextLabel?.text = String(userDefaults.integerForKey(audioDeviceListKey))
        case .AllowNotifications:
            cell.switchCellLabel?.text = "Allow Notifications"
            cell.userInteractionEnabled = false
        case .ShowCloudMusic:
            cell.switchCellLabel?.text = "Show Cloud Music"
        case .Acknowledgments:
            cell.textLabel?.text = "Acknowledgements"
            cell.detailTextLabel?.text = ""
        case .Version:
            cell.textLabel?.text = "Version"
            cell.detailTextLabel?.text = buildVersion
            cell.detailTextLabel?.textColor = UIColor.lightGrayColor()
            cell.userInteractionEnabled = false
        }
        // Return the cell
        return cell
    } else {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)

        // Switch through each cell, and implement the labels/setup for each row
        // The order of the cases is irrelevant!
        switch sections[indexPath.section].items[indexPath.row] {
        case .AudioDevices:
            cell.textLabel?.text = "Audio Devices"
            cell.detailTextLabel?.text = String(userDefaults.integerForKey(audioDeviceListKey))
        case .AllowNotifications:
            cell.switchCellLabel?.text = "Allow Notifications"
            cell.userInteractionEnabled = false
        case .ShowCloudMusic:
            cell.switchCellLabel?.text = "Show Cloud Music"
        case .Acknowledgments:
            cell.textLabel?.text = "Acknowledgements"
            cell.detailTextLabel?.text = ""
        case .Version:
            cell.textLabel?.text = "Version"
            cell.detailTextLabel?.text = buildVersion
            cell.detailTextLabel?.textColor = UIColor.lightGrayColor()
            cell.userInteractionEnabled = false
        }
        // Return the cell
        return cell
    }
}
  

Комментарии:

1. покажите свой код celForRowAtIndexPath и скриншот вашего контроллера просмотра.

2. Добавлено по запросу

3. Должен ли я иметь все случаи в обоих или только соответствующие?

4. Почему вы возвращаете ячейку 2 раза в одном состоянии?

5. просто измените цвет ячейки bg или любой другой визуальный эффект на основе условия включения / выключения.

Ответ №2:

пожалуйста, используйте это

    if cellIdentifier == "SwitchCell" {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SwitchTableViewCell
        return cell
    } else {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
        return cell
    }
  

доступ к метке с тегом, подобным этому, в той ячейке, где вы не определяете выходы

 if let theLabel = self.view.viewWithTag(123) as? UILabel {
        theLabel.text = "some text"
    }
  

Комментарии:

1. @Shyam мое удовольствие.