ios - 如何使用 UICollectionView 的 selectItem 在 collectionView 单元格上绘制?

标签 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 func buttonPressed 中看到选择并滚动到一个随机日期,然后在 collectionView 中选择该单元格。然后,在覆盖 var isSelected 函数中使用 arrowImage.isHidden = !isSelected 绘制单元格的箭头。

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

最佳答案

1- 添加一个 reloadCell 函数来改变单元格的用户界面。然后,您应该从 awakeFromNib 函数中删除 override var isSelectedarrowImage.isHidden = true

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

2- 您应该在 ViewController.swift class private 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
}

}

关于ios - 如何使用 UICollectionView 的 selectItem 在 collectionView 单元格上绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52614010/

相关文章:

ios - 由于未捕获的异常 'NSGenericException' 而终止应用程序,原因 : 'Unable to activate constraint with anchors

ios - 为什么这个 UIWebView 到 UIImage 的代码会呈现一个空白图像?

swift - Siesta是否支持HTTP长轮询

ios - 调用 `reloadItems(at:)` 导致程序崩溃

ios - UICollectionView 在顶部加载项目 - 加载更多选项

ios - 滚动时 uicollectionviewcell 中的图像加载错误

ios - 新 iTunes 连接中的 IPA 大小错误?

ios - 绘制 CIImage 的背景颜色

iOS MapBox map 滞后

swift - 无法覆盖泛型类的子类中的初始化程序