如何在iOS (Xcode) 的提交按钮内实现分段控制?

How to implement segmented control inside submit button in iOS (Xcode)?

我在提交按钮内有一个针对性别的分段控件,但是,它给出了一个错误说明:

"Cannot assign value of type "String" 输入 "UISegmentedControl!" "

有谁知道如何在按钮内正确编码分段控件,以便当用户单击提交按钮时,它会在页面上显示所选的性别?

编辑:我要回答的问题是:

"Implement an App that include input fields for Name, Address and a Stepper (for Age) and two Segmented Controls (for “Male/Female” and “Enrolled/Not Enrolled”). When the user clicks on a submit button, it displays the message on the page such as Hello Name, Address: Address, Age: Age, Gender: Male/Female, Status: Enrolled/Not Enrolled. "

这是我的编码:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var nametxt: UITextField!
@IBOutlet weak var age: UIStepper!
@IBOutlet weak var addresstxt: UITextField!
@IBOutlet weak var status: UISegmentedControl!
@IBOutlet weak var gender: UISegmentedControl!
@IBOutlet weak var display: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()

    age.wraps = true
    age.autorepeat = true
    age.maximumValue = 100
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func submit(_ sender: Any) {
    var txtname : String
    var txtaddress : String
    txtname = nametxt.text!
    txtaddress = addresstxt.text!


    if self.gender.selectedSegmentIndex == 0 {
        gender = "male"
    }

    if self.gender.selectedSegmentIndex == 1 {
        gender = "female"
    }

    display.text = "Hello " + txtname + ", " + "Address: " + txtaddress  
    + ", " + "Gender: " + gender

  }
 }

编译器简单描述了发生此错误的原因:) 只需使用 String 而不是 SegmentControl... gender 是 SegmentControl 类型,因此您不能将其与其他字符串连接...

使用titleForSegment(at:)获得正确的字符串值

display.text = "Hello " + txtname + ", " + "Address: " + txtaddress<br> + ", " + "Gender: " + gender.titleForSegment(在:gender.selectedSegmentIndex)

并且你可以摆脱上面的条件...

其他选项是在 IBAction

中设置新的私有 属性
@IBAction func submit(_ sender: Any) {
    // Fixed your codestyle and semantics as well
    let txtname = nametxt.text ?? "missing name"
    let txtaddress = addresstxt.text ?? "missing address"

    let txtgender = gender.titleForSegment(at: gender.selectedSegmentIndex)
    display.text = "Hello " + txtname + ", " + "Address: " + txtaddress  
    + ", " + "Gender: " + txtgender

  }
 }

`https://developer.apple.com/documentation/uikit/uisegmentedcontrol/1618561-titleforsegment