Swift计算器的弧度和度数模式之间的UISwitch

时间:2016-03-07 17:50:15

标签: ios swift calculator

我一直在关注斯坦福斯威夫特教程,我为大部分任务提供了有效的解决方案。

但是,我想实现一个启用弧度/度数模式的UISwitch函数。

我已经完成了这个功能,但我似乎找不到让它工作的方法 - 它不断给我弧度默认答案,而不是程度。

请帮我改进代码

CalculatorEngine.swift

// this is the conversion function
func sind(degrees: Double) -> Double {
    return sin(degrees * 180 / M_PI)
}

ViewController.swift

 class ViewController: UIViewController {

@IBOutlet weak var switch: UISwitch!

@IBOutlet weak var labelDisplay: UILabel!


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
}




// this function is supposed to call conversion function once switch is On
    @IBAction func switchTogOnOff(sender: UISwitch) {
        for button5 in [radButton, degButton] {
            button5.hidden = !button5.hidden
        }

        if mySwitch.on {
            engine.sind(displayValue)

        }   
        else {
            displayValue = 0
        }

    }

1 个答案:

答案 0 :(得分:0)

有多种方法可以做到这一点,一种方法是在CalculatorEngine

中声明转换因子
var unitTransformFactor: Double = 1

并在度和弧度之间切换时更改其值

@IBAction func switchTogOnOff(sender: UISwitch) {
   ...

   var degreesSelected: Bool = mySwitch.on

   // there are better ways to write to do this but it will work
   self.engine.unitTransformFactor = degreesSelected ? M_PI / 180 : 1.0
}

然后您可以在引擎中声明您的数学运算

func sinOperation(angle: Double) -> Double {
   return sin(angle * self.unitTransformFactor)
}

func asinOperation(value: Double) -> Double {
   return asin(value) / self.unitTransformFactor
}

并将它们用作:

knownOps["sin"] = Op.UnaryOperation("sin", sinOperation)
...
knownOps["sin⁻¹"] = Op.UnaryOperation("sin⁻¹", asinOperation)

顺便说一句,您的sind函数无法正常工作,您必须将度数乘以M_PI并除以180,而不是相反。