如何使用 segmentedControl 的 selectedIndex 获取数组的相应索引

How can I use the selectedIndex of a segmentedControl to get the corresponding index of array

我的代码:

class HomeViewController: UITableViewController {
    var segmentedControl: HMSegmentedControl!
    var text = [
        // 名词
        ["音读名词","训读名词","音读与训读的分辨方法"],
        // 形容词
        ["如何分辨形容词", "常用形容词", "形容词的变形规则"]
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        configForSegmentedControl()
    }

    func configForSegmentedControl() {
        segmentedControl = HMSegmentedControl(sectionTitles: ["名词","形容词","形容动词","片假名单词","动词","复合动词"])
        segmentedControl.frame = CGRectMake(0, 0, self.view.bounds.width, 44)
        segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10)
        segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe
        segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown
        segmentedControl.addTarget(self, action: #selector(HomeViewController.segmentedControlChangedValue(_:)), forControlEvents: UIControlEvents.ValueChanged)
        if let font = UIFont(name: "BigYoungMediumGB2.0", size: 15) {
            segmentedControl.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: font]
        }
        segmentedControl.backgroundColor = UIColor.whiteColor()
        segmentedControl.selectionIndicatorHeight = 3
        segmentedControl.selectionIndicatorColor = UIColor.blackColor()

        tableView.tableHeaderView = segmentedControl
    }

    func segmentedControlChangedValue(segmentedControl: HMSegmentedControl) {
        print("Selected index \(segmentedControl.selectedSegmentIndex) (via UIControlEventValueChanged)")
    }
}

extension HomeViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return text[segmentedControl.selectedSegmentIndex].count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        print("cellForRowAtIndexPath:\(segmentedControl.selectedSegmentIndex)")
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        cell.textLabel?.text = text[segmentedControl.selectedSegmentIndex][indexPath.row]
        return cell
    }
}

控制台输出如下:

cellForRowAtIndexPath:0
cellForRowAtIndexPath:0
cellForRowAtIndexPath:0
Selected index 1 (via UIControlEventValueChanged)
Selected index 0 (via UIControlEventValueChanged)

cellForRowAtIndexPathsegmentedControlChangedValue 之前被调用,这就是为什么我无法获得正确的索引来获取文本数组元素的原因。所以我该怎么做?

供将来评论参考: 如果你想要 cellForRow 中的值,那么你应该在 'segmentedControlChangedValue'

中重新加载 tableview

一般情况下,要根据 selection/action 设置单元格,您应该根据要求重新加载/开始更新表视图