Getting info from UITextField

百般思念 提交于 2021-02-07 04:47:30

问题


I have a UITextField and I ask the user to input some data using the number pad.

  • Is the data that comes out a string or an integer?
  • How do I multiply the number they input by 10 then output it to a label?

回答1:


Just use the text attribute of the UITextField to get the value (which is a String).

Then, use the toInt() method (which returns an optional) to convert that to an Integer, so that you can perform mathematical operations.

@IBOutlet weak var field: UITextField!
@IBOutlet weak var label: UILabel!

@IBAction func getVal () {
     var text: String = field.text
     var multipliedNum: Int = 0

     if let num = text.toInt() {
         multipliedNum = num * 10
     }

     label.text = "\(multipliedNum)"
}



回答2:


Xcode 9 with Swift

//Get reference of UITextView
@IBOutlet weak var inputMealName: UITextField! 

//Get value of input from UITextView in variable
let name: String = inputMealName.text!

//Use input value eg. show alert
  let alert = UIAlertController(title: "Alert", message: name, preferredStyle: UIAlertControllerStyle.alert)

    alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)



回答3:


You can get the string via the UITextField attribute.

  • the data comes out a string. You can use string methods(intValue , doubleValue....etc) convert string value to a number.

  • when you get the number , you can set the label output via its text attribute.



来源:https://stackoverflow.com/questions/25859986/getting-info-from-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!