Swift中使用自定义分段控件时CollectionCell数据显示问题

CollectionCell data display question when using custom segmented control in Swift

我参考“http://bitly.kr/fDz2Ma”做了一个自定义的分段控件。但是,当我 select 一个特定的项目时,我需要查看与该项目匹配的集合视图单元格,但是我没有找到分段控件的 selected 索引。

到目前为止,我已经创建了自定义分段控件,但尚未找到 selected 索引按钮项。

import UIKit

class MainBookViewController: UIViewController {

@IBOutlet weak var interfaceSegmented: CustomSegmentedControl! {
    didSet{
        interfaceSegmented.setButtonTitles(buttonTitles: ["A","B","C"])
        interfaceSegmented.selectorViewColor = .red
        interfaceSegmented.selectorTextColor = .red
    }
}


override func viewDidLoad() {
    super.viewDidLoad()

    codeSegmentedConfig()
}

func codeSegmentedConfig() {
    let codeSegmented = CustomSegmentedControl(frame: CGRect(x: 0, y: 90, width: self.view.frame.width, height: 50), buttonTitle: ["A","B","C""])
    codeSegmented.backgroundColor = .clear
    view.addSubview(codeSegmented)
}

}

extension MainBookViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView
        .dequeueReusableCell(withReuseIdentifier: "MainBookCell", for: indexPath) as! MainBookCell

        cell.bookTitleLabel.text = "apple"
        cell.bookWriterLabel.text = "me"
        cell.bookImageView.image = UIImage(named: "3")

        return cell
    }
}

如果我只知道selected自定义分段控件的按钮索引,我想使用case语句将集合视图单元格中的数据更改为索引号。

如果我只知道 selected 按钮项的索引,我打算使用 CollectionViewDataSource 代码中的 case 语句修改集合视图单元格。

如果我正确理解了你的问题,你可以通过这样做来实现:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        switch interfaceSegmented.selectedSegmentIndex {
          case 0:
            //do something when selected segment index is 0
          case 1:
            //do something when selected segment index is 1
          default:
            break
    }