Как изменить данные в ячейке в динамическом проекте xcode UITableView? - PullRequest
0 голосов
/ 29 ноября 2018

У меня есть представление таблицы динамических прототипов с разными ячейками, я добавляю ячейки в представление таблицы и хочу изменить их содержимое.Все учебники, которые я найду, предназначены для просмотра таблицы только с одним типом ячеек, но у меня есть 8 различных типов.Как бы я изменил их содержимое (т. Е. Текстовые поля и т. Д.) И как я мог бы получить действия от них обратно к основному контроллеру табличного представления для выполнения бизнес-логики?(то есть нажатие кнопки и т. д.)

Что я сделал:

  1. Я создал класс костюма для каждого типа ячейки и соединил их в customClass, поле класса.

    enter image description here

  2. Я приложил текстовые поля и т. Д., Действия и ссылки на эти классы.

  3. thisмоя функция cellAtRow я предполагаю, что я бы как-то изменил в этой функции?или ссылаться на классы отсюда?

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    
        print ("indexPath: ", indexPath)
        print ("indexPath: ", indexPath[0])
        print ("-------")
    
        if (sectionsData[indexPath[0]] == "header") {
            let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath)
    
            return cell
    
        } else if (sectionsData[indexPath[0]] == "description") {
            let cell = tableView.dequeueReusableCell(withIdentifier: "headerInfoCell", for: indexPath)
    
            return cell
    
        } else if (sectionsData[indexPath[0]] == "diagnoses") {
            let cell = tableView.dequeueReusableCell(withIdentifier: "diagnosisCell", for: indexPath)
    
            return cell
    
        } else if (sectionsData[indexPath[0]] == "perscription") {
            let cell = tableView.dequeueReusableCell(withIdentifier: "perscriptionCell", for: indexPath)
    
            return cell
    
        } else if (sectionsData[indexPath[0]] == "notes") {
            let cell = tableView.dequeueReusableCell(withIdentifier: "notesCell", for: indexPath)
    
            return cell
    
        } else if (sectionsData[indexPath[0]] == "addFaxHeadline") {
    
            let cell = tableView.dequeueReusableCell(withIdentifier: "addFaxCell", for: indexPath)
    
            return cell
    
        } else if (sectionsData[indexPath[0]] == "addFax") {
    
            let cell = tableView.dequeueReusableCell(withIdentifier: "emailNameCell", for: indexPath)
    
            return cell
    
    
        } else if (sectionsData[indexPath[0]] == "addEmailHeadline") {
    
            let cell = tableView.dequeueReusableCell(withIdentifier: "addEmailCell", for: indexPath)
    
            return cell
    
    
        } else if (sectionsData[indexPath[0]] == "addEmails") {
    
            let cell = tableView.dequeueReusableCell(withIdentifier: "emailNameCell", for: indexPath)
    
            return cell
    
    
        } else if (sectionsData[indexPath[0]] == "givePermissionHeadline") {
    
            let cell = tableView.dequeueReusableCell(withIdentifier: "permissionCell", for: indexPath)
    
            return cell
    
        } else if (sectionsData[indexPath[0]] == "select answer") {
    
            let cell = tableView.dequeueReusableCell(withIdentifier: "selectAnswerCell", for: indexPath)
    
            return cell
        }
    

Ответы [ 4 ]

0 голосов
/ 29 ноября 2018

Как указано в документации Apple , тип возврата dequeueReusableCell равен UITableViewCell .

Apple Documentation Return Value: A UITableViewCell object with the associated identifier or nil if no such object exists in the reusable-cell queue.

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

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

За настройку каждая ячейка отвечает за свою собственную конфигурацию.У вас должна быть функция (вы можете использовать протоколы или наследовать от суперкласса) и внутри cellForRowAtIndexPath, после ее приведения, вызвать функцию установки.

customCell.setup() //you can add some parameters if its needed

0 голосов
/ 29 ноября 2018

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

if (sectionsData[indexPath[0]] == "header") {
    let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath) as! HeaderTableViewCell

    cell.titleLbl.text = "Title"
    cell.delegate = self // To receive actions back

    return cell
}

. . . // More of the same

// default return

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

protocol HeadTableViewCellProcol{
    func bttnPressed()
}

class HeadTableViewCell: UITableViewCell{

    var delegate: HeadTableViewCellProcol?

    @IBAction func bttnPressedInCell(){
        delegate?.bttnPressed()
    }
}

Это из этих протоколов, таких как протоколы, которые вы должны были реализовать для вашего UITableView.Вам также нужно будет внедрить эти протоколы в ваш основной VC.

0 голосов
/ 29 ноября 2018

Вам нужно привести UITableViewCell в ваш класс динамических ячеек.Вы можете попробовать следующее:

guard let cell = tableView. dequeueReusableCell(withIdentifier: "perscription", for: indexPath) as? PerscriptionTableViewCell else { return UITableViewCell() }

cell.setupCell() //You have access to cell's public funcs and vars now
return cell

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

0 голосов
/ 29 ноября 2018

Вам нужно использовать

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

для вызова cell.yourTextField.text, например

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