如何将UISegmentedControl类型转换为int进行计算?

时间:2015-01-23 23:57:16

标签: user-interface swift operators uisegmentedcontrol

快速编程的新手。我正在创建一个应用程序,使用简单的UI界面为用户进行计算。在我从UITextfield(var weight)收到输入后,我想从UISegmentedControl给出的输入中划分该值。如何从UISegmentedControl获取值并将其转换为int,以便它可以从var权重中划分..这是我的代码

import UIKit

class FirstViewController: UIViewController {

@IBOutlet weak var weight: UITextField!


@IBOutlet weak var reps: UISegmentedControl!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func Calculate(sender: UIButton) {


    NSLog("Weight = \(weight.text)")

    NSLog("reps = \(reps.selectedSegmentIndex)")

}

}

1 个答案:

答案 0 :(得分:2)

如果你想获得所选UISegmentedControl的值,你可以这样做:

var myInt:Int = reps.titleForSegmentAtIndex(reps.selectedSegmentIndex)!.toInt()!

但是我强烈建议你使用double作为你选择的类型,因为int对于计算来说并不是那么好。所以你必须将你的字符串转换成双重字符串:

var myRepsDouble = (reps.titleForSegmentAtIndex(reps.selectedSegmentIndex)! as NSString).doubleValue

此外,如果你想用UITextField的值计算,你还必须将它强制转换为double,因为你无法用字符串计算:

var myTextFieldDouble = (weight.text as NSString).doubleValue