如何在iOS(Xcode)中的“提交”按钮内实现分段控件?

时间:2018-10-06 07:18:24

标签: ios swift loops button segmentedcontrol

我在“提交”按钮中有一个按性别划分的控件,但是,它显示了一个错误:

“无法将类型为” String“的值分配为类型为” UISegmentedControl!“”

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

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

“实施一个包含名称,地址和步进器(针对年龄)的输入字段以及两个分段控件(针对“男性/女性”和“已注册/未注册”的输入框的应用程序。)当用户单击提交按钮时,它会在页面上显示消息,例如Hello Name,地址:地址,年龄:年龄,性别:男性/女性,状态:已注册/未注册。”

这是我的编码:

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

  }
 }

1 个答案:

答案 0 :(得分:1)

发生此错误的原因仅由编译器描述:)只需使用String代替SegmentControl ...性别是SegmentControl类型,因此您无法将其与其他字符串连接...

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

display.text = "Hello " + txtname + ", " + "Address: " + txtaddress
+ ", " + "Gender: " + gender.titleForSegment(at: 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