在分段控件中调用按钮动作

Calling button actions in segmented control

我有一个分段控制动作的方法,有两段

@IBAction func segmentChanged(_ sender: UISegmentedControl) { 

    // What goes here for displaying data similar to buttonsTapped? 
}

我有如下三个按钮

 @IBOutlet weak var buttonOne: UIButton!
 @IBOutlet weak var buttonTwo: UIButton!
 @IBOutlet weak var buttonThree: UIButton!

我有所有 3 个按钮的操作方法,

 @IBAction func buttonsTapped(_ sender: UIButton) { 

    switch sender {
    case buttonOne:
     print("Button one Tapped")
    case buttonTwo:
     print("Button two tapped")
    case buttonThree:
     print("Button three tapped")
    default: break
    }

  if segmentedControl.selectedSegmentIndex == 0
        {
            print("First Segment")
        }
        else
        {
            print("Second Segment")
        }
  }

当我点击 buttonOne 时,我得到 "First Segment""Button One Tapped",因为它在第一段中。同样,buttonTwo 和 buttonThree 在控制台上显示正确的消息。

但是当我更改分段控件时,我在控制台上没有收到任何消息。我尝试在 segmentChanged 方法中调用 buttonOne.sendActions(for: .touchUpInside),但它仅适用于 buttonOne 并会弄乱其他人。当段更改时,如何为所有按钮和段获取正确的消息?提前致谢。

更改的段控制值将使用以下方法记录

   @IBAction func segmentChanged(_ sender: UISegmentedControl) { 
    if sender.selectedSegmentIndex == 0
            {
                print("First Segment")
            }
            else
            {
                print("Second Segment")
            }
    }

按钮操作将使用以下方法记录:

@IBAction func buttonsTapped(_ sender: UIButton) { 

    switch sender {

    case buttonOne:
     print("Button one Tapped")
    case buttonTwo:
     print("Button two tapped")
    case buttonThree:
     print("Button three tapped")
    default: break
    }
}

这两种方法不能结合使用,因为按钮关联到 touch-up 内部事件和分段控件关联到值更改事件

您需要为 .valueChange 而不是 .touchUpInside 设置 UISegmentedControl 方法。

看起来如下:

并添加以下方法。

代码:

@IBOutlet weak var buttonOne            : UIButton!
@IBOutlet weak var buttonTwo            : UIButton!
@IBOutlet weak var buttonThree          : UIButton!
@IBOutlet weak var segmentedControl     : UISegmentedControl!

var selectedButton                      : UIButton!

@IBAction func buttonsTapped(_ sender: UIButton) {

    selectedButton = sender

    switch sender {

    case buttonOne:
        print("Button one Tapped")

    case buttonTwo:
        print("Button two tapped")

    case buttonThree:
        print("Button three tapped")

    default: break
    }

    if self.segmentedControl.selectedSegmentIndex == 0 {
        print("First Segment")
    } else {
        print("Second Segment")
    }
}


@IBAction func segmentChanged(_ sender: UISegmentedControl) {
    if sender.selectedSegmentIndex == 0
    {
        self.selectedButton.sendActions(for: .touchUpInside)
    }
    else
    {
        self.selectedButton.sendActions(for: .touchUpInside)
    }
}