Swift - 如何获取嵌入到 UITableView 单元格中的选定控件段?

Swift - How to get selected segment of control embedded in a UITableView cell?

我在 UIViewController 中有一个 UITableView。有两个自定义单元格。其中之一有一个 UISegmentedControl。

到目前为止,还不错。

当我点击控件时,分段控件值发生变化,IBAction 函数按预期运行。

问题是所选索引始终显示为 -1(也就是未选择任何内容)。

我在这里错过了什么?

这是值更改的代码:

 @IBAction func recurranceChanged(sender: UISegmentedControl?) {

        print ("index: ", recurrenceControl.selectedSegmentIndex) << This returns -1

        if recurrenceControl.selectedSegmentIndex == 0 {
            print("No ")
        }

        if recurrenceControl.selectedSegmentIndex == 1 {
            print("Sometimes ")

        }


        if recurrenceControl.selectedSegmentIndex == 2 {
            print("Yes")

        }

    }

试试这个:(同时从 UISegmentedControl 中删除了“?”,因为它不需要。)

@IBAction func recurranceChanged(sender: UISegmentedControl) {

    print ("index: ", sender.selectedSegmentIndex)

    if sender.selectedSegmentIndex == 0 {
        print("No ")
    }

    if sender.selectedSegmentIndex == 1 {
        print("Sometimes ")

    }


    if sender.selectedSegmentIndex == 2 {
        print("Yes")

    }

}

这应该可以解决问题 ;)

所以我不知道 answer/question 是仅在静态 table 视图中完成,还是通过向 customCellController 添加 IBAction 来完成,但这效果不佳。例如,跨多个 table 视图重复使用一个单元格(我的案例)将导致单元格控制器中的 if 语句过多(例如,对于每个 table 视图)或导致应用程序崩溃。

另一种方法是,在每个单元格

中向 SegmentedControl 添加一个目标

Swift 5

CustomCell.swift

@IBOutlet weak var mSC: UISegmentedControl!

ViewController.swift

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     //
     let cell = tableView.dequeueReusableCell(withIdentifier: "textCellIdentifier", for: indexPath) as! CustomCell
     cell.mSC.addTarget(self, action: #selector(ViewController.onSegChange(_:)), for: .valueChanged)
 }


//This function is called when the segment control value is changed
@objc func onSegChange(_ sender: UISegmentedControl) {

    //REPLACE tableview to your tableview var
    let touchPoint = sender.convert(CGPoint.zero, to: self.tableview)
    let tappedIndexPath = tableview.indexPathForRow(at: touchPoint)

    print("SECTION: \(tappedIndexPath!.section)")
    print("ROW #: \(tappedIndexPath!.row)")
    print("SEG CON INDEX: \(sender.selectedSegmentIndex)")
    print("Tapped")

}

我知道这个问题比较老,但我希望这对像我一样的人有所帮助。