Skip to content

Instantly share code, notes, and snippets.

@akio0911
Forked from kenji272/ViewController.swift
Created April 20, 2015 01:41
Show Gist options
  • Save akio0911/98306a11843184f1460d to your computer and use it in GitHub Desktop.
Save akio0911/98306a11843184f1460d to your computer and use it in GitHub Desktop.
import UIKit
enum CalculationEnum: Int {
case PLUS
case MINUS
case TIMES
case DIVIDE
func calculate(target1: Double, target2: Double) -> Double {
switch self {
case .PLUS:
return target1 + target2
case .MINUS:
return target1 - target2
case .TIMES:
return target1 * target2
case .DIVIDE:
return target1 / target2
}
}
}
class ViewController: UIViewController {
@IBOutlet weak var numberTextField1: UITextField!
@IBOutlet weak var numberTextField2: UITextField!
@IBOutlet weak var calculationType: UISegmentedControl!
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet var tapGesture: UITapGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
// ジェスチャー追加
self.view.addGestureRecognizer(self.tapGesture)
}
@IBAction func calculate(sender: AnyObject) {
let selectedType: Int = self.calculationType.selectedSegmentIndex
// 0除算チェック
// 2番目のテキストフィールドがブランクでもエラーが出るのでそこも考慮に入れたチェック
if selectedType == CalculationEnum.fromRaw(3) && isZeroDivide() {
self.resultLabel.text = "割る数には0以外を入力してください"
return
}
let calEnum = CalculationEnum(rawValue: selectedType)
let target1 = (self.numberTextField1.text as NSString).doubleValue
let target2 = (self.numberTextField2.text as NSString).doubleValue
// 計算処理
var result = calEnum!.calculate(target1, target2: target2)
self.resultLabel.text = "\(result)"
}
// 0除算になっているか
func isZeroDivide() -> Bool {
if self.numberTextField2.text.isEmpty || self.numberTextField2.text == "0" {
return true
}
return false
}
// キーボード外をタップしてナンバーパッドを閉じる
@IBAction func closeNumberPad(sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment