Не удается удалить представление из суперпредставления в ячейке многократного использования таблицы - PullRequest
0 голосов
/ 25 декабря 2018
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: EventCommentsCustom = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! EventCommentsCustom
       guard let release = array[exist: indexPath.section] else { return cell }

    if release.user == "condition" {

                let image = UIImage()
                let imageView = UIImageView(image: image)
                imageView.sd_setImage(with: URL(string: "https://example.com/" + TegKeychain.get("profile_pic")!))
                imageView.frame = CGRect(x: 20, y: 10, width: 50, height:50)
                imageView.layer.borderWidth = 0.4
                imageView.layer.masksToBounds = false
                imageView.layer.borderColor = UIColor.gray.cgColor
                imageView.layer.cornerRadius = 25
                imageView.clipsToBounds = true
                imageView.tag = 3
                cell.addSubview(imageView)

                let button = UIButton(frame: CGRect(x: 90, y: 10, width: 200, height: 50))
                button.contentHorizontalAlignment = .left
                button.setTitleColor(UIColor.lightGray, for: .normal)
                button.setTitle(NSLocalizedString("Say something...", comment: ""), for: .normal)
                button.addTarget(self, action: #selector(EventComments.openInput), for: .touchUpInside)
                button.tag = 3
                cell.addSubview(button)

    } else {

    if let viewWithTag = cell.viewWithTag(3) {
                    if viewWithTag is UIImageView {
                        print("DONE")
                        viewWithTag.removeFromSuperview()
                    }
                }
                if let viewWithTag = cell.viewWithTag(3) {
                    if viewWithTag is UIButton {
                        print("DONE")
                        viewWithTag.removeFromSuperview()
                    }
                }
    }

 return cell
}

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

Однако, я все еще вижу UIButton и UIImageview при первом повторном использовании (5. раздел таблицы), затем он начинает правильно удаляться

Почему они не удаляются при первом повторном использовании?

1 Ответ

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

Полагаю, что повторное использование в вашем случае может означать, что представление изображения и кнопка добавляются дважды для ячейки.Вы удаляете только один из них, хотя.Я думаю, что вы должны принять во внимание другой подход (например, разные клетки-прототипы, как указано @vadian), но сейчас (если мое предположение верно), вы можете попробовать это, чтобы решить вашу проблему:

Заменить ...

if let viewWithTag = cell.viewWithTag(3) {
    if viewWithTag is UIImageView {
        print("DONE")
        viewWithTag.removeFromSuperview()
    }
}
if let viewWithTag = cell.viewWithTag(3) {
    if viewWithTag is UIButton {
        print("DONE")
        viewWithTag.removeFromSuperview()
    }
}

С ...

while let viewToRemove = cell.viewWithTag(3) {
    if viewToRemove is UIImageView || viewToRemove is UIButton {
        viewToRemove.removeFromSuperview()
    }
}

Обновление - Подход с различными типами ячеек будет выглядеть примерно так:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let release = array[exist: indexPath.section] else { return cell }

    if release.user == "condition" {
        let cell = tableView.dequeueReusableCell(withIdentifier: "OneIdentifier", for: indexPath) as! OneCustomCellType
        // configure your cell
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AnotherIdentifier", for: indexPath) as! AnotherCustomCellType
        // configure your cell
        return cell
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...