Swift Way to display variables

Asked

Viewed 126 times

0

I’m finishing a small project to learn Swift but there is a small problem in joining more variables in the output.

@IBOutlet weak var Nome: UITextField!
 @IBAction func CalcularIMC(_ sender: AnyObject) {

    imc = ((p * 200) / (a * a)) * 100 / 2
    var str = "";

    if imc < 16
    {
        str = NSString(format: "O seu IMC é %.2f, Peso Abaixo", imc) as String
        lblresultado.backgroundColor = UIColor.orange
}
 lblresultado.text = str;

There’s definitely some parentheses missing, but it was just for show. My problem is here :

(format: "O seu IMC é %.2f, Peso Abaixo", imc)

In this text I also want to show the variable Nome which is at the beginning of the code I showed you.

2 answers

1

Look at it this way:

str = NSString(format: "%@ o seu IMC é %.2f, Peso Abaixo", nome, imc) as String
  • Gave me error while displaying text. <uitextfield: 0x79e964e0; frame.... text = " The name I wrote" clipstobound... a thing like this s:

  • It seems to me that name is not a string.

  • Name is text. It will be the user name for example : Maria

  • Try it this way: str = Nsstring(format: "%@ your BMI is %.2f, Weight Down", "Maria", imc) as String

  • This is how it works:

  • So. This means that no text is coming to the function. The function needs to receive a string and name is not a string. It seems to me that it is an object. You must pass something, like: Name.Text. I don’t have SWIFT here to validate it, but go that way.

  • To receive Var Name I created a text box . @Iboutlet Weak var Name: Uitextfield!

Show 2 more comments

1


The native Swift type is not Nsstring, but String. All initializers available for Nsstring also exist for String. If you want to put the text of your text field directly in your string you have to do it as follows:

str = String(format: "%@ o seu IMC é %.2f, Peso Abaixo", Nome.text!, imc)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.