Swift - данные не отображаются должным образом при использовании tableView.dequeueReusableCell - PullRequest
0 голосов
/ 01 мая 2019

Когда определенные кнопки нажимаются в приложении, их имя, время начала и окончания, когда они были нажаты, отображаются в UITableView.

Это работало нормально при использовании пользовательского UITableViewCell, но после установки tableView.dequeueReusableCell вместо этого UITableView показывает первую ячейку в виде белой пустой ячейки, когда она предназначена для отображения данных.Если добавлено больше данных, теперь отображается первый невидимый ввод, но последний ввод отсутствует / скрыт.

Я нашел похожие вопросы и реализовал то, что казалось основным виновником, но это не сработалодля меня.

    timelineTableView.contentInsetAdjustmentBehavior = .never
    timelineScrollViewContainer.contentInsetAdjustmentBehavior = .never
    timelineTableView.contentOffset = .zero

Я также пытался изменить высоту секции, но безрезультатно.

Стоит отметить, что данные не отображаются должным образом в UITableView, но все еще сохраняютсяправильно в plist.

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

У Doeanyonene есть другое решение?спасибо за помощь

метод cellForRowAt

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

    if tableView ==  timelineTableView {

       //let cell = TimelineCell(frame: CGRect(x: 0, y: 0, width: 100, height: 40), title: "test", startTime: "test", endTime: "test", rawStart: "") // Used previously before using dequeueReusableCell

        var cell: TimelineCell = tableView.dequeueReusableCell(withIdentifier: timelineCellId, for: indexPath) as! TimelineCell

        if let marker = markUpPlist.arrayObjects.filter({$0.UUIDpic == endClipSelectedMarkerUUID}).first {
            cell = TimelineCell(frame: CGRect(x: 0, y: 0, width: 100, height: 40), title: "test", startTime: "test", endTime: "test", rawStart: "")
            cell.backgroundColor = marker.colour
            cell.cellLabelTitle.text = marker.name
            cell.cellUUID.text = marker.UUIDpic

            if let timeline = chronData.rows.filter({$0.rowName == marker.name}).first {
                if let start = timeline.clips.last?.str {
                    cell.cellStartTime.text = chronTimeEdited(time: Double(start))
                    cell.cellStartRaw.text = String(start)
                }
                if let end = timeline.clips.last?.end {
                    cell.cellEndTime.text = chronTimeEdited(time: Double(end))
                }
            }
        }
        return cell
}

TimelineCell.swift

class TimelineCell : UITableViewCell {

var cellLabelTitle: UILabel!
var cellStartTime: UILabel!
var cellEndTime: UILabel!
var cellStartRaw: UILabel!
var cellUUID: UILabel!

init(frame: CGRect, title: String , startTime: String, endTime: String, rawStart: String) {
    super.init(style: UITableViewCell.CellStyle.default, reuseIdentifier: "timelineCellId")

    backgroundColor = UIColor(red: 29/255.0, green: 30/255.0, blue: 33/255.0, alpha: 1.0)

    cellLabelTitle = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    cellLabelTitle.translatesAutoresizingMaskIntoConstraints = false
    cellLabelTitle.textColor = UIColor.black

    addSubview(cellLabelTitle)

    cellLabelTitle.widthAnchor.constraint(equalToConstant: 80).isActive = true
    cellLabelTitle.heightAnchor.constraint(equalToConstant: 30).isActive = true
    cellLabelTitle.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0).isActive = true
    cellLabelTitle.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true

    cellStartTime = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    cellStartTime.translatesAutoresizingMaskIntoConstraints = false
    cellStartTime.textColor = UIColor.black

    addSubview(cellStartTime)

    cellStartTime.widthAnchor.constraint(equalToConstant: 80).isActive = true
    cellStartTime.heightAnchor.constraint(equalToConstant: 30).isActive = true
    cellStartTime.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0).isActive = true
    cellStartTime.leftAnchor.constraint(equalTo: cellLabelTitle.rightAnchor, constant: 10).isActive = true

    cellEndTime = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    cellEndTime.translatesAutoresizingMaskIntoConstraints = false
    cellEndTime.textColor = UIColor.black

    addSubview(cellEndTime)

    cellEndTime.widthAnchor.constraint(equalToConstant: 80).isActive = true
    cellEndTime.heightAnchor.constraint(equalToConstant: 30).isActive = true
    cellEndTime.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0).isActive = true
    cellEndTime.leftAnchor.constraint(equalTo: cellStartTime.rightAnchor, constant: 10).isActive = true

    cellStartRaw = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    cellUUID = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    addSubview(cellStartRaw)
    addSubview(cellUUID)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
}
}

Создать просмотр таблицы

    timelineTableView.frame = CGRect(x: 0, y: 0, width: sideView.frame.width, height: sideView.frame.size.height)
    timelineTableView.delegate = self
    timelineTableView.dataSource = self
    timelineTableView.register(TimelineCell.self, forCellReuseIdentifier: timelineCellId)
    timelineTableView.translatesAutoresizingMaskIntoConstraints = false
    timelineTableView.separatorStyle = .none
    timelineTableView.backgroundColor = Style.BackgroundColor
    timelineTableView.contentInsetAdjustmentBehavior = .never
    timelineScrollViewContainer.contentInsetAdjustmentBehavior = .never
    timelineScrollViewContainer.addSubview(timelineTableView)
    timelineTableView.contentOffset = .zero

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

 let cell = TimelineCell(frame: CGRect(x: 0, y: 0, width: 100, height: 40), title: "test", startTime: "test", endTime: "test", rawStart: "")

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

var cell: TimelineCell = tableView.dequeueReusableCell(withIdentifier: timelineCellId, for: indexPath) as! TimelineCell

1 Ответ

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

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

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

    var cell: TimelineCell = tableView.dequeueReusableCell(withIdentifier: timelineCellId, for: indexPath) as! TimelineCell

    let marker = markUpPListFiltered
    cell.backgroundColor = marker.colour
    cell.cellLabelTitle.text = marker.name
    cell.cellUUID.text = marker.UUIDpic
    if let timeline = chronData.rows.filter({$0.rowName == marker.name}).first {
       if let start = timeline.clips.last?.str {
           cell.cellStartTime.text = chronTimeEdited(time: Double(start))
           cell.cellStartRaw.text = String(start)
       }
       else
       {
           cell.cellStartTime.text = ""
           cell.cellStartRaw.text = ""
       }
       if let end = timeline.clips.last?.end {
           cell.cellEndTime.text = chronTimeEdited(time: Double(end))
       }          
       else
       {
           cell.cellEndTime.text = ""
       }
    }
    return cell
}

Предполагается, что существует массив для отфильтрованных отсортированных данных, который называется markupPListFiltered.Подготовьте это в viewDidLoad или в другом месте.Вы не показали другие методы источника данных, поэтому я предполагаю, что вы можете изменить их по мере необходимости, например,

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
  return markupPListFiltered.count
}

TimelineCell нуждается в c'or для удаления данных.Вам следует подумать об использовании раскадровки для создания своих ячеек и связать виджеты с выходами (см. Любой из сотен учебных пособий по табличным представлениям, я бы порекомендовал Рэя Вендерлиха в качестве хорошего начального источника).

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