我有一个按钮,它为尝试分数标签添加1,然后按一个按钮,根据按下的按钮将1或0添加到正确的分数标签。然后将此数据传递给各种viewControllers。在最后一个viewController上我想将标签中的字符串转换为int,然后进行简单的计算以获得百分比。我试过的代码如下。百分比没有显示,所以我认为我没有正确转换它?
在之前的VC上,aScore和cScore被设置为= 0的变量。例如..
var aScore = 0
var cScore = 0
我在VC之间传递数据,然后在最终的viewController上传递以下代码。
import UIKit
class gViewController: UIViewController {
@IBOutlet weak var correctScore: UILabel!
@IBOutlet weak var attemptScore: UILabel!
@IBOutlet weak var percentage: UILabel!
var aScore: Int!
var cScore: Int!
var percentage1: Int!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
correctScore.text = NSString(format: "%i", cScore) as String
attemptScore.text = NSString(format: "%i", aScore) as String
let c:Int? = Int(correctScore.text!)
let a:Int? = Int(attemptScore.text!)
percentage1 = c!/a!
percentage.text = NSString(format: "%i", percentage1) as String
}
答案 0 :(得分:0)
试试这个
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.correctScore.text = String(format: "%.1f", cScore)
self.attemptScore.text = String(format: "%.1f", aScore)
var percentage1 = Float(cScore)/Float(aScore)
self.percentage.text = String(format: "%.1f", percentage1)
}