繁体   English   中英

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")

    }

}

这应该可以解决问题;)

所以我不知道答案/问题是在静态 tableview 中完成还是通过向 customCellController 添加 IBAction 来完成,但这并不能很好地工作。 例如,跨多个表格视图(我的案例)重用单元格将导致单元格控制器中的 if 语句过多(例如,对于每个表格视图)或导致应用程序崩溃。

另一种方法是,在每个单元格中向SegmentedControl添加一个目标

斯威夫特 5

CustomCell.swift

@IBOutlet weak var mSC: UISegmentedControl!

视图控制器.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")

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM