Skip to content

Instantly share code, notes, and snippets.

@kenji272
Created April 17, 2015 16:07
Show Gist options
  • Save kenji272/61ce14e9e7c3b3950c55 to your computer and use it in GitHub Desktop.
Save kenji272/61ce14e9e7c3b3950c55 to your computer and use it in GitHub Desktop.
【課題】Part2 足し算・引き算・掛け算・割り算するアプリを作る
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 == 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