如何不通过选择器Swift将参数传递给方法?

时间:2018-09-06 00:13:00

标签: swift function methods

我在Swift中有一个应用程序,该应用程序在页面上具有多个UISegmentedControls,它们都具有相同的目标,即“ answerClicked”方法。但是,我需要一种将信息传递给该方法的方法,即只需单击WHICH UISegmentedControl。

我知道参数不能通过选择器传递-有什么方法可以获取此信息并将其传递给“ answerClicked”方法?

class Flowchart{
    //Init segmented controls up here...

    segmentedControl0.addTarget(self, action: #selector(answerClicked), for: .valueChanged)
    segmentedControl1.addTarget(self, action: #selector(answerClicked), for: .valueChanged)
    segmentedControl2.addTarget(self, action: #selector(answerClicked), for: .valueChanged)    

    @objc func answerClicked(){
        //Ideally would have an argument "segmentedControlNumber: Int"
        //How else to tell 0, 1, and 2 apart?
    }
}

2 个答案:

答案 0 :(得分:3)

为每个tag设置UISegmentedControl属性,然后使用作为值更改方法的第一个参数发送的sender来获取{{1} }:

tag

注意:如@rmaddy在评论中所述,最好避免使用标记class Flowchart { //Init segmented controls up here... func setup() { segmentedControl1.addTarget(self, action: #selector(answerClicked), for: .valueChanged) segmentedControl1.tag = 1 segmentedControl2.addTarget(self, action: #selector(answerClicked), for: .valueChanged) segmentedControl2.tag = 2 segmentedControl3.addTarget(self, action: #selector(answerClicked), for: .valueChanged) segmentedControl3.tag = 3 } @objc func answerClicked(_ sender: UISegmentedControl) { switch sender.tag { case 1: // code to handle segmentedControl1 case 2: // code to handle segmentedControl2 case 3: // code to handle segmentedControl3 default: break } } } ,因为默认情况下所有视图都接收标记值0。我从0开始重命名了您的分段控件。

答案 1 :(得分:2)

Vacawama的答案很好用,非常适合您要问的问题,但是我建议不要使用标签。他们很脆弱。您必须记住要在情节提要中设置标签,如果您更改了内容,很容易忘记维护它们。

相反,我建议在Vacawama的答案中使用发件人来确定利用了哪个控件:

var controls: [UISegmentedControl]!

override func viewDidLoad() {
  super.viewDidLoad()
  controls = [segmentedControl1, segmentedControl2, segmentedControl3]
}

@IBAction func answerClicked(_ sender: UISegmentedControl) {
    if let index = controls.index( { where sender === $0 } ) {
       //act on your index
    } else {
       //error case; could not find sender in controls array. (Should not happen)
    }
}

编辑:

或者,如果您要使用switch语句,则可以这样编写:

@IBAction func answerClicked(_ sender: UISegmentedControl) {
  switch sender {
     case segmentedControl1:
        //code for control 1
     case segmentedControl2:
        //code for control 2
     case segmentedControl3:
        //code for control 3
     default: 
        //error case
        //break
   }
}