ios - 重置 UITableViewCell 无法正常工作/未选择的单元格在滚动后显示为选中

标签 ios swift uitableview uicollectionview prepareforreuse

enter image description here

问题是当我在选择 collectionViewCell(日期 28 上的紫色)后滚动 tableview 时。 tableview 底部的几个 CollectionViewCells 似乎被选中(这里的 CollectionView 存在于 TableView 中)。

代码是这样的:

class ViewController: UIViewController {

    @IBOutlet weak var tblView: UITableView!

    var storedOffsets = [Int: CGFloat]()           // Will be used by JTAppleCalender
    let formatter = DateFormatter()                // NSDateFormatter


    override func viewDidLoad() {
        super.viewDidLoad()

        self.tblView.delegate = self
        self.tblView.dataSource = self
        self.tblView.reloadData()
    }

    func handleCellConfiguration(cell: JTAppleCell?, cellState: CellState) {
        handleCellSelection(view: cell, cellState: cellState)
    }


    func handleCellSelection(view: JTAppleCell?, cellState: CellState) {

        guard let myCustomCell = view as? CalenderCell else {return }
        if cellState.isSelected {
            myCustomCell.contentView.layer.cornerRadius = 10
            myCustomCell.contentView.backgroundColor = UIColor.init(red: 0.26, green: 0.10, blue: 0.39, alpha: 1.0)
        } else {
            myCustomCell.contentView.layer.cornerRadius =  0
            myCustomCell.contentView.backgroundColor = UIColor.clear
        }
    }
}

UITableViewCell:

class TableCell: UITableViewCell{

    @IBOutlet weak var lbldate: UILabel!
    @IBOutlet weak var collectionViewDate: JTAppleCalendarView!


    override func prepareForReuse() {
        super.prepareForReuse()

      }
}

extension TableCell {

    func setCollectionViewDataSourceDelegate<D: JTAppleCalendarViewDataSource & JTAppleCalendarViewDelegate>(_ dataSourceDelegate: D, forRow row: Int) {

        collectionViewDate.calendarDelegate = dataSourceDelegate
        collectionViewDate.calendarDataSource = dataSourceDelegate
        collectionViewDate.tag = row
        collectionViewDate.setContentOffset(collectionViewDate.contentOffset, animated:false)
        collectionViewDate.reloadData()
    }

    var collectionViewOffset: CGFloat {
        set { collectionViewDate.contentOffset.x = newValue }
        get { return collectionViewDate.contentOffset.x }
    }
}


extension ViewController : UITableViewDataSource, UITableViewDelegate{

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

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

        let cell = self.tblView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell

        cell.lbldate.text = "date "+"\(indexPath.row)"
        return cell
    }


    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        guard let tableViewCell = cell as? TableCell else { return }
        tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
        tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
    }

    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        guard let tableViewCell = cell as? TableCell else { return }
        storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset
    }

}


class CalenderCell: JTAppleCell{

    @IBOutlet weak var lblDate: UILabel!
}




extension ViewController: JTAppleCalendarViewDataSource , JTAppleCalendarViewDelegate {


    func calendar(_ calendar: JTAppleCalendarView, willDisplay cell: JTAppleCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) {
        let myCustomCell = cell as! CalenderCell
        sharedFunctionToConfigureCell(myCustomCell: myCustomCell, cellState: cellState, date: date)
    }

    func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell {

        let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "CalenderCell", for: indexPath) as! CalenderCell
        cell.lblDate.text = cellState.text
        self.calendar(calendar, willDisplay: cell, forItemAt: date, cellState: cellState, indexPath: indexPath)

        return cell
    }

    func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
        handleCellConfiguration(cell: cell, cellState: cellState)
    }

    func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) {

        handleCellConfiguration(cell: cell, cellState: cellState)
    }

    func sharedFunctionToConfigureCell(myCustomCell: CalenderCell, cellState: CellState, date: Date) {
        handleCellConfiguration(cell: myCustomCell, cellState: cellState)
    }

    func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {

        let currentDate = Date()
        let endDate = Calendar.current.date(byAdding: .month, value: 4, to: Date())
        let parameters = ConfigurationParameters(startDate: currentDate,
                                                 endDate: endDate!,
                                                 numberOfRows: 1,
                                                 generateInDates: .forFirstMonthOnly,
                                                 generateOutDates: .off,
                                                 hasStrictBoundaries: false)
        calendar.scrollToDate(currentDate, triggerScrollToDateDelegate: false, animateScroll: false)
        return parameters
    }

    func configureVisibleCell(myCustomCell: CalenderCell, cellState: CellState, date: Date) {
        handleCellConfiguration(cell: myCustomCell, cellState: cellState)
    }

}

如果我需要添加任何其他内容,请告诉我。

最佳答案

这不是使用 JTAppleCalendar CollectionView 的推荐方式。 您必须存储在某些数据源变量中选择的日期以及何时选择/取消选择单元格。重新加载时,根据此存储值,您必须相应地突出显示单元格。

//This will store the selected dates against the cell rows.
var selectedDatesVsIndex = [Int : Date]()

在 JTAppleCalendar 委托(delegate)的选择/取消选择方法上,将所选日期添加到维护 rowIndex -> DateSelected 的 localDictionary。

   func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
        cell?.isSelected = true
        selectedDatesVsIndex.merge([calendar.tag : date]) { (d1, d2) -> Date in return d1 }

        calendar.reloadData()
//        handleCellConfiguration(cell: cell, cellState: cellState)
    }


  func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
        cell?.isSelected = false
        selectedDatesVsIndex.removeValue(forKey: calendar.tag)
        calendar.reloadData()

//        handleCellConfiguration(cell: cell, cellState: cellState)
    }

除此之外,我在 TableViewCells 中将标签设置为 indexpath.row。同时添加了 Collection View 的 reload 方法。像这样

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

        let cell = self.tblView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell
        cell.tag = indexPath.row
        cell.collectionViewDate.tag = indexPath.row
        cell.collectionViewDate.reloadData()

        cell.lbldate.text = "date "+"\(indexPath.row)"
        return cell
    }

显示选定背景颜色的单元格自定义应在 CellForRowAt Index 中完成。

 func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell {

        let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "CalenderCell", for: indexPath) as! CalenderCell
        cell.lblDate.text = cellState.text
        cell.backgroundColor =  UIColor.clear

        if selectedDatesVsIndex.keys.index(of: calendar.tag) != nil {
            if let object = selectedDatesVsIndex[calendar.tag] , object.compare(date) == .orderedSame {
                cell.backgroundColor = UIColor.gray
            }
        }
 //       self.calendar(calendar, willDisplay: cell, forItemAt: date, cellState: cellState, indexPath: indexPath)

        return cell
    }

请删除其他杂乱的方法,如

 override func prepareForReuse() {
        super.prepareForReuse()

//        let hasContentView = self.subviews .contains(self.contentView)
//        if(hasContentView){
//            self.contentView.removeFromSuperview()
//        }
    }

关于ios - 重置 UITableViewCell 无法正常工作/未选择的单元格在滚动后显示为选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51514438/

相关文章:

ios - 如何使我的按钮在抽屉导航中居中并使用 swift 删除边缘阴影?

ios - tableview 静态单元格动态页脚

iOS-indexPath 总是返回 nil

objective-c - Clean NSLog - 没有时间戳和程序名称

ios - 任何手指扫描示例教程iPhone SDK

ios - 一旦出现 uicontroller 扫描蓝牙设备

swift - 取消 Facebook 身份验证时,(快速)项目崩溃

arrays - 按多个数组对 Tableview 行进行排序

ios - 如何以编程方式在自定义表格 View 中附加搜索栏

iphone - UITextField 中的问题在 iPhone 的 UIImageView 中添加?