简体   繁体   English

Swift 2.0和Xcode-beta 7.0 –使用UITextField进行数字输入

[英]Swift 2.0 and Xcode-beta 7.0 – Using UITextField for numeric input

Completely frustrated noob here. 完全沮丧的菜鸟在这里。 Surely this isn't as hard as it looks? 当然这并不像看起来那样难吗?

I want to use a number entered by the user, perform a calculation, and send the result back to the screen. 我想使用用户输入的数字,进行计算,然后将结果发送回屏幕。

I have code working that can use a string forced in by code, convert it to double, do the math and send the result to the screen. 我的代码可以使用代码强制输入的字符串,将其转换为double值,进行数学运算并将结果发送到屏幕。 For example: 例如:

 @IBAction func buttonPressed() {
  NSLog("Button Pressed")

  let decimalAsString = "123.45"
  let decimalAsDouble = NSNumberFormatter().numberFromString(decimalAsString as String)!.doubleValue
   TempLabel.text = "\(decimalAsDouble+2.45)"
}

This simply adds 2.45 to the string "123.45" and sends the result 125.9 back as a string to my label for display, all when the button is pressed. 只需将2.45添加到字符串“ 123.45”,然后将结果125.9作为字符串发送回我的标签以进行显示,所有这些操作都在按下按钮时进行。 Great. 大。 This simpler form also works: 这种更简单的形式也适用:

        let decimalAsDouble = Double(decimalAsString)

What I have been struggling with is using a number entered into the UITextField. 我一直在努力使用的是在UITextField中输入的数字。

My UITextField uses a decimal pad for entry, and I've always had a number entered there when the errors were thrown. 我的UITextField使用小数点输入,当抛出错误时,我一直在其中输入数字。 (Or did I? The numbers show on screen but are they really "entered"? Hmmm...) (还是我?数字显示在屏幕上,但它们确实是“输入”的吗?嗯……)

No matter what I try, I cannot find code that will both compile and then not blow up at execution, when the button is pressed. 无论我尝试什么,当按下按钮时,我都找不到同时编译并且不会在执行时崩溃的代码。 The error I get generally complains about unwrapping an optional nil. 我得到的错误通常抱怨解开一个可选的nil。

I can detail some of the things that DON'T work, if that helps. 如果有帮助,我可以详细说明一些不起作用的内容。

OK, well I've finally solved my own problem. 好吧,好了,我终于解决了自己的问题。 My problem was with closing the entry field and dismissing the numeric entry pad. 我的问题是关闭输入字段并关闭数字输入板。 Once I did that, the entered value became available. 一旦执行此操作,输入的值将变为可用。

The critical code, in the view controller, was: 在视图控制器中,关键代码是:

func textFieldShouldReturn(textField: UITextField!) -> Bool {   //delegate method
    textField.resignFirstResponder()
    return true
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
    view.endEditing(true)
    super.touchesBegan(touches, withEvent: event)
}

This dismisses the entry pad when the user clicks anywhere in the view except for the field itself or a button. 当用户单击视图中除字段本身或按钮之外的任何位置时,这将关闭输入板。 Programming that looks for the entered value doesn't blow up. 查找输入值的程序不会中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM