Вот мой код в ячейке для метода строки: -
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(.journalListingCell, for: indexPath) as! JournalListViewCell
cell.delegate = self
//fetching the category model as per the category id
if let category = categories?.first(where: { $0.categoryID == dreamJournalArray[indexPath.row].categoryID }) {
cell.configureCell(dreamJournalArray[indexPath.row], category)
}
return cell
}
Этот код просто сопоставляет идентификатор категории из массива категорий с идентификатором категории в основной модели данных и передает эту категорию в модель ячейки конфигурации вместе с моделью данных.
Метод настройки ячейки выглядит следующим образом:
typealias Model = DreamJournalModel
func configureCell(_ model: Model, _ category: CategoryModel) {
//setting the gradient colors
verticalView.backgroundColor = category.categoryGradientColor(style: .topToBottom, frame: verticalView.frame, colors: [UIColor.init(hexString: category.initialGradientColor)!, UIColor.init(hexString: category.lastGradientColor)!])
horizontalVIew.backgroundColor = category.categoryGradientColor(style: .leftToRight, frame: self.frame, colors: [ UIColor.init(hexString: category.lastGradientColor)!, UIColor.init(hexString: category.initialGradientColor)!])
timelineCircleView.backgroundColor = category.categoryGradientColor(style: .topToBottom, frame: timelineCircleView.frame, colors: [UIColor.init(hexString: category.initialGradientColor)!, UIColor.init(hexString: category.lastGradientColor)!])
// setting the intention matching image as per the rating
intentionImageView.image = UIImage.init(named: "Match\(model.intentionMatchRating)")
// setting up the date of the journal recorded
let date = Date(unixTimestamp: model.createdAt!)
dateMonthLabel.text = (date.monthName(ofStyle: .threeLetters)).uppercased()
dateNumberLabel.text = String(date.day)
//setting the titles and labels
dreamTitleLabel.text = model.title
dreamTagsLabel.text = model.tags
// setting the lucid icon
gotLucidImageview.isHidden = !(model.isLucid!)
//setting the buttons text or image
if model.recordingPath != nil {
addRecordButton.setTitle(nil, for: .normal)
addRecordButton.backgroundColor = UIColor.clear
addRecordButton.layer.cornerRadius = 0
addRecordButton.setImage(LRAsset.cardRecording.image, for: .normal)
}
else{
addRecordButton.setTitle(" + RECORD ", for: .normal)
addRecordButton.backgroundColor = UIColor.blackColorWithOpacity()
addRecordButton.layer.cornerRadius = addRecordButton.bounds.height/2
addRecordButton.setImage(nil, for: .normal)
}
if model.note != nil {
addNoteButton.setTitle(nil, for: .normal)
addNoteButton.backgroundColor = UIColor.clear
addNoteButton.layer.cornerRadius = 0
addNoteButton.setImage(LRAsset.cardNote.image, for: .normal)
}
else{
addNoteButton.setTitle(" + NOTE ", for: .normal)
addNoteButton.backgroundColor = UIColor.blackColorWithOpacity()
addNoteButton.layer.cornerRadius = addRecordButton.bounds.height/2
addNoteButton.setImage(nil, for: .normal)
}
if model.sketchPath != nil {
addSketchButton.setTitle(nil, for: .normal)
addSketchButton.backgroundColor = UIColor.clear
addSketchButton.layer.cornerRadius = 0
addSketchButton.setImage(LRAsset.CardSketch.image, for: .normal)
}
else{
addSketchButton.setTitle(" + SKETCH ", for: .normal)
addSketchButton.backgroundColor = UIColor.blackColorWithOpacity()
addSketchButton.layer.cornerRadius = addSketchButton.bounds.height/2
addSketchButton.setImage(nil, for: .normal)
}
}
В этом методе я устанавливаю цвета градиента в ячейке в соответствии с категорией. И затем я устанавливаю состояния кнопок внизу в соответствии с указанными условиями.
Вот как выглядит моя таблица: -
3 кнопки в нижней части ячейки находятся в представлении стека, и их внешний вид динамически меняется в зависимости от условий.
Табличное представление не прокручивается плавно, и задержка очень заметна невооруженным глазом. Высота ячейки зафиксирована на уровне 205,0 и определяется высотой для метода индекса строки. Я не знаю, где моя выборка и передача данных в логику ячейки ошибочна. Пожалуйста, помогите, если прокрутка может быть улучшена здесь. Заранее спасибо.
(NS)DateFormatter
, я надеюсь, что она всегда одна и та же, и вы не выделяете/инициируете ее каждый раз. Кроме того, избегайте, возможно, фильтрации каждый раз, когда категория, и постарайтесь иметь модель, которая имеет ее непосредственно в соответствии с желаемым идентификатором категории (проверьте ее, каждый раз указывая один в indexPath, даже если это не правильная категория, это просто для скорости/ запаздывающие тесты). Другими словами: найдите строки, которые замедляют ваш код. - person Larme   schedule 08.07.2018