如何使用UICollectionView的selectItem绘制collectionView单元格?

时间:2018-10-02 18:08:18

标签: ios swift uicollectionview

我添加了我在这里工作的仓库:

https://github.com/AlexMarshall12/singleDayTimeline/tree/master/singleDayTimeline

基本上,我有900个collectionView单元(具有自定义XIB布局)。

    let cellIdentifier = "DayCollectionViewCell"
class ViewController: UIViewController, UICollectionViewDataSource,UICollectionViewDelegate {

    @IBOutlet weak var button: UIButton!
    var dates = [Date?]()
    var startDate: Date?
    @IBOutlet weak var daysCollectionView: UICollectionView!
    override func viewDidLoad() {
        super.viewDidLoad()
        daysCollectionView.register(UINib.init(nibName: "DayCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: cellIdentifier)

        let allDates = Helper.generateRandomDate(daysBack: 900, numberOf: 10)
        self.dates = allDates.sorted(by: {
            $0!.compare($1!) == .orderedAscending
        })
        startDate = self.dates.first! ?? Date()

        daysCollectionView.delegate = self
        daysCollectionView.dataSource = self
        // Do any additional setup after loading the view, typically from a nib.
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 900
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = daysCollectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! DayCollectionViewCell

        let cellDate = Calendar.current.date(byAdding: .day, value: indexPath.item, to: self.startDate!)

        if Calendar.current.component(.day, from: cellDate!) == 15 {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "MMM"
            let monthString = dateFormatter.string(from: cellDate!)
            cell.drawMonth(month: monthString)
        }
        if Calendar.current.component(.day, from: cellDate!) == 1 && Calendar.current.component(.month, from: cellDate!) == 1 {
            print("drawYEAR")
            cell.drawYear(year:Calendar.current.component(.year, from: cellDate!))
        }
        if self.dates.contains(where: { Calendar.current.isDate(cellDate!, inSameDayAs: $0!) }) {
            print("same")
            cell.backgroundColor = UIColor.red
        } else {
            print("not me")
            //cell.backgroundColor = UIColor.lightGray
        }
        return cell
    }

//    func collectionView(_ collectionView: UICollectionView,
//                        layout collectionViewLayout: UICollectionViewLayout,
//                        sizeForItemAt indexPath: IndexPath) -> CGSize {
//        return CGSize(width: 2, height: daysCollectionView.bounds.size.height/2 )
//    }
    @IBAction func buttonPressed(_ sender: Any) {

        let randomIndex = Int(arc4random_uniform(UInt32(self.dates.count)))
        let randomDate = self.dates[randomIndex]
        let daysFrom = randomDate?.days(from: self.startDate!)
        let indexPath = IndexPath(row: daysFrom!, section: 0)
//        if let cell = daysCollectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as DayCollectionViewCell? {
//            print("found it")
//        } else {
//            print("didn't find it")
//        }
        daysCollectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredHorizontally)
        daysCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    }
    }

然后是单元格:

   class DayCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var arrowImage: UIImageView!

    override var isSelected: Bool{
        didSet{
            arrowImage.isHidden = !isSelected
        }
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        arrowImage.isHidden = true
    }

    override func prepareForReuse() {
        self.backgroundColor = UIColor.clear
    }

    func drawMonth(month: String){

    }
    func drawYear(year: Int){

    }

}

它看起来像这样:

enter image description here

因此计划是,当按下该按钮时,您可以在@IBAction函数funcbuttonPressed中看到,选择了一个随机日期并滚动到该日期,然后在collectionView中选择了该单元格。然后,在覆盖var isSelected函数中使用arrowImage.isHidden = !isSelected绘制单元格的箭头。

当前,这几乎可以正常工作。当随机选择的新索引离当前索引足够远时,箭头将在所选单元格下方重绘。我的理论是,如果索引差异足够大,则下一个单元尚未加载/出队,因此永远不会调用isSelected。但是我仍然不确定为什么它不能正常工作

1 个答案:

答案 0 :(得分:1)

1-添加reloadCell函数以更改单元格的ui。然后,您应该从override var isSelected函数中删除arrowImage.isHidden = trueawakeFromNib

func reloadCell(_ isSelected:Bool){
   arrowImage.isHidden = !isSelected
}

2-您应在ViewController.swiftprivate var selectedIndexPath: IndexPath?上定义一个变量,然后应添加此代码以检查箭头是否被隐藏。

 if let selectedRow = selectedIndexPath {
     cell.reloadCell(selectedRow == indexPath)
 } else {
     cell.reloadCell(false)
 } 

3-并且,如果您像下面这样更改按钮操作功能,则可以使用。

@IBAction func buttonPressed(_ sender: Any) {

    let randomIndex = Int(arc4random_uniform(UInt32(self.dates.count)))
    let randomDate = self.dates[randomIndex]
    let daysFrom = randomDate?.days(from: self.startDate!)
    let indexPath = IndexPath(row: daysFrom!, section: 0)
    self.selectedIndexPath = indexPath;

    daysCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    daysCollectionView.reloadData()
}
  • 所有代码在这里。

ViewController.swift

import UIKit
let cellIdentifier = "DayCollectionViewCell"
class ViewController: UIViewController, UICollectionViewDataSource,UICollectionViewDelegate {

@IBOutlet weak var button: UIButton!
var dates = [Date?]()
var startDate: Date?
private var selectedIndexPath: IndexPath?

@IBOutlet weak var daysCollectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    daysCollectionView.register(UINib.init(nibName: "DayCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: cellIdentifier)

    let allDates = Helper.generateRandomDate(daysBack: 900, numberOf: 10)
    self.dates = allDates.sorted(by: {
        $0!.compare($1!) == .orderedAscending
    })
    startDate = self.dates.first! ?? Date()

    daysCollectionView.delegate = self
    daysCollectionView.dataSource = self
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 900
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = daysCollectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! DayCollectionViewCell

    let cellDate = Calendar.current.date(byAdding: .day, value: indexPath.item, to: self.startDate!)

    if let selectedRow = selectedIndexPath {
        cell.reloadCell(selectedRow == indexPath)
    } else {
        cell.reloadCell(false)
    }

    if Calendar.current.component(.day, from: cellDate!) == 15 {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM"
        let monthString = dateFormatter.string(from: cellDate!)
        cell.drawMonth(month: monthString)
    }
    if Calendar.current.component(.day, from: cellDate!) == 1 && Calendar.current.component(.month, from: cellDate!) == 1 {
        print("drawYEAR")
        cell.drawYear(year:Calendar.current.component(.year, from: cellDate!))
    }
    if self.dates.contains(where: { Calendar.current.isDate(cellDate!, inSameDayAs: $0!) }) {
        print("same")
        cell.backgroundColor = UIColor.red
    } else {
        print("not me")
        //cell.backgroundColor = UIColor.lightGray
    }
    return cell
}

@IBAction func buttonPressed(_ sender: Any) {

    let randomIndex = Int(arc4random_uniform(UInt32(self.dates.count)))
    let randomDate = self.dates[randomIndex]
    let daysFrom = randomDate?.days(from: self.startDate!)
    let indexPath = IndexPath(row: daysFrom!, section: 0)
    self.selectedIndexPath = indexPath;

    //daysCollectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredHorizontally)
    daysCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    daysCollectionView.reloadData()
}

}

DayCollectionViewCell.swift

import UIKit

class DayCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var arrowImage: UIImageView!

override func awakeFromNib() {
    super.awakeFromNib()
}

override func prepareForReuse() {
    self.backgroundColor = UIColor.clear
}

func drawMonth(month: String){

}
func drawYear(year: Int){

}

func reloadCell(_ isSelected:Bool){
    arrowImage.isHidden = !isSelected
}

}