iosswiftloopsbuttonsegmentedcontrol

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


I have a segmented control for gender inside the submit button, however, it gives an error stating:

"Cannot assign value of type "String" to type "UISegmentedControl!" "

Does anybody know how to properly code segmented controls inside a button so that when the user clicks on a submit button, it displays the selected gender on the page?

EDIT: The question I am trying to answer is:

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

Here is my coding:

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

  }
 }

Solution

  • The reason why this error occur is simply described by the compiler :) Just use String instead of SegmentControl... gender is type SegmentControl so you cannot concatenate it with other strings...

    use titleForSegment(at:) to get the right string value

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

    And you can get rid of the conditions above...

    Other option is to set new private property inside the 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