如何根据 segmentedControl 索引更改数据

How to change data based on segmentedControl index

我正在尝试根据段控件的索引更改 collectionView 的数据。当我 运行 我的代码崩溃时。有人可以告诉我我在这里做错了什么吗?我正在遵循我发现的不同方法。我在崩溃时得到的错误代码是

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1da72fde0)

当我尝试在段索引之间切换时出现错误。并发生在线上

cell.trendsLabel.text = maleTrends[indexPath.row]

 func handleSegControlTapped(for header: HomeViewHeaderReusableView)


 var header: HomeViewHeaderReusableView?



    func handleSegControlTapped(for header: HomeViewHeaderReusableView) {

        collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems) 

        switch header.segmentedControl?.selectedSegmentIndex {
        case 0:
            print("Display female trends")

            header.segmentedControl?.selectedSegmentIndex = 0

            let indexPath = IndexPath()
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "homeViewCell", for: indexPath) as! CurrentTrendsCell
            cell.trendsLabel.text = femaleTrends[indexPath.row]
            cell.trendsImageView.image = femaleImages[indexPath.row]

        case 1:
            print("Display male trends")
            header.segmentedControl?.selectedSegmentIndex = 1
            let indexPath = IndexPath()

            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "homeViewCell", for: indexPath) as! CurrentTrendsCell
                     cell.trendsLabel.text = maleTrends[indexPath.row]
            cell.trendsImageView.image = maleImages[indexPath.row]

        default:
            break
        }

        collectionView.reloadData()

    }



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

        let segmentedOutlet = header?.segmentedControl

        switch segmentedOutlet?.selectedSegmentIndex {
        case 0: return femaleTrends.count

       case 1: return maleTrends.count

        default: print("opps, cant load data")
        }

        return 0

    }


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

        let segmentedOutlet = header?.segmentedControl

        switch segmentedOutlet?.selectedSegmentIndex {
        case 0: cell.trendsLabel.text = femaleTrends[indexPath.row]
        cell.trendsImageView.image = femaleImages[indexPath.row]

        case 1: cell.trendsLabel.text = maleTrends[indexPath.row]
        cell.trendsImageView.image = maleImages[indexPath.row]

        default: break

        }
        return cell


    }

  func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "homeViewReuseCell", for: indexPath) as! HomeViewHeaderReusableView

        headerView.delegate = self 
        return headerView
    }


编辑

这是header

中的代码

class HomeViewHeaderReusableView: UICollectionReusableView {

    @IBOutlet weak var segmentedControl: UISegmentedControl?


    var delegate: HomeSegmentedControl?



     // MARK: Handler
    @objc func handleSegTapped() {
        delegate?.handleSegControlTapped(for: self)
    }



    @IBAction func segmentedTapped(_ sender: Any) {
        handleSegTapped()

        // change data based on female / male


    }


 override func awakeFromNib() {
         super.awakeFromNib()

        segmentedControl?.tintColor = .clear
        segmentedControl?.layer.borderColor = UIColor.clear.cgColor
        segmentedControl?.setBackgroundImage(UIImage(), for: .normal, barMetrics: .default)


        segmentedControl?.setTitleTextAttributes([
            NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 11),
            NSAttributedString.Key.foregroundColor: UIColor.lightGray

            ], for: .normal)

        segmentedControl?.setTitleTextAttributes([
            NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 11) ,
            NSAttributedString.Key.foregroundColor: UIColor.white
            ], for: .selected)


        segmentedControl?.selectedSegmentIndex = 0



    }


根据您对段的选择,只需重新加载 collectionView 并在 cellForItemAt 中配置 CollectionViewCell

无论您在何处添加段控件,都只会真正对操作方法做出反应并相应地更新集合。

永远,永远不会cellForRow/ cellForItem之外调用dequeueReusableCell。该单元格已出队,但在方法退出时会被释放。与 collection/table 查看数据源方法不同,单元格不会在任何地方返回。

编辑:

替换

var header: HomeViewHeaderReusableView?

var selectedSegmentIndex = 0

然后将整个方法handleSegControlTapped替换为

func handleSegControlTapped(for header: HomeViewHeaderReusableView) {
    selectedSegmentIndex = header.segmentedControl!.selectedSegmentIndex
    collectionView.reloadData()
}

由于数据源方法处理分段控件的状态,只需重新加载集合视图就足够了。

然后把numberOfItemsInSection改成

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

    switch selectedSegmentIndex {
    case 0: return femaleTrends.count
    case 1: return maleTrends.count
    default: print("opps, cant load data")
       return 0
    }
}

并相应地更改其他数据源方法。