问题描述
我已经习惯了C#和Java,Swift绝对是另一种野兽!
I'm used to C# and java, swift is definitely a different beast!
我一直在努力几个小时才能使它正常工作.这也是很简单的事情!我只想从UITextField中获取文本并将其转换为Int,然后将Int发送到UILabel!
I've been struggling for hours trying to get this to work. It is something so simple as well! I just want to get the text from a UITextField and turn it into an Int and then send the Int to a UILabel!!
互联网上的许多答案根本没有用!
So many answers on the internet haven't worked at all!
这是我现在遇到的错误. (使用Xcode 8.2.1和Swift 3.0.2 )
This is the error i'm getting now. (using Xcode 8.2.1 and Swift 3.0.2)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var firstTextField: UITextField!
@IBOutlet weak var secondTextField: UITextField!
@IBOutlet weak var sumLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func calculateButton(_ sender: UIButton) {
let firstNumber = Int(firstTextField.text!)
let secondNumber = Int(secondTextField.text!)
//ERROR: 'init' has been renamed to 'init'(describing:)'
sumLabel.text = String(firstNumber + secondNumber)
}
}
谢谢大家!
推荐答案
首先获取Int
:
let firstNumber = Int(firstTextField.text!) ?? 0
当无法将文本解析为Int
时,?? 0
提供默认值.
The ?? 0
provides a default value when the text cannot be parsed to an Int
.
转换回String
很简单:
sumLabel.text = String(firstNumber)
但是,如果要获取分组分隔符,则可能要使用NumberFormatter
.
However, you might want to use NumberFormatter
instead if you want to get grouping separators.
这篇关于UITextField转换为UILabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!