import UIKit
class ViewController: UIViewController {
import UIKit
class ViewController: UIViewController {
//計算結果を表示するラベルを宣言
var resultLabel = UILabel()
let xButtonCount = 4 //一行に配置するボタンの数
let yButtonCount = 4
//画面の横幅サイズを格納するメンバ変数
let screenWidth:Double = Double(UIScreen.mainScreen().bounds.size.width)
//画面の縦
let screenHeight:Double = Double(UIScreen.mainScreen().bounds.size.height)
//ボタン間の余白
let buttonMargin = 10.0
//計算結果表示
var resultArea = 0.0
override func viewDidLoad() {
super.viewDidLoad()
//画面全体の縦幅に応じて計算結果表示エリアの縦幅を決定
switch screenHeight{
case 480:
resultArea = 200.0
case 568:
resultArea = 250.0
case 667:
resultArea = 300.0
case 736:
resultArea = 350.0
default:
resultArea = 0.0
}
//計算結果のラベル
resultLabel.frame = CGRect(x:10, y:30, width:screenWidth-20, height:resultArea-30)
let buttonLabels = [
"7","8","9","×",
"4","5","6","-",
"1","2","3","+",
"0","C","÷","="
]
for var y=0; y<yButtonCount; y++ {
for var x=0; x<xButtonCount; x++ {
//計算機のボタン作成
var button = UIButton()
//ボタンの横幅
var buttonWidth = (screenWidth - (buttonMargin * (Double(xButtonCount)+1)))/Double(xButtonCount)
//ボタンの縦幅
var buttonHeight = (screenHeight - resultArea - ((buttonMargin*Double(yButtonCount)+1)))/Double(yButtonCount)
//ボタンのx座標
var buttonPositionX = (screenWidth - buttonMargin) / Double(xButtonCount) * Double(x) + buttonMargin
//ボタンのy座標
var buttonPositionY = (screenHeight - resultArea - buttonMargin) / Double(yButtonCount) * Double(y) + buttonMargin + resultArea
//ボタンの配置、サイズ
button.frame = CGRect(x:buttonPositionX, y:buttonPositionY, width:buttonWidth, height:buttonHeight)
//背景
button.backgroundColor = UIColor.greenColor()
//ボタンのラベルタイトル
var buttonNumber = y * xButtonCount + x
//ボタンのラベルタイトルを取り出すインデックス番号
button.setTitle(buttonLabels[buttonNumber],forState: UIControlState.Normal)
//ボタンタップ時のアクション
button.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
//ボタン配置
self.view.addSubview(button)
}
}
}
//計算結果ラベル設定する
resultLabel.backgroundColor = UIColor.grayColor()
resultLabel.font = UIFont(name:"Arial", size: 50)
resultLabel.textAlignment = NSTextAlignment.Right
resultLabel.numberOfLines = 4
resultLabel.text = "0"
//計算結果ラベルをviewcontrollerクラスのviewに設置
self.view.addSubview(resultLabel)
//ボタンタップメソッド
func buttonTapped(sender:UIButton){
var tappedButtonTitle:String = sender.titleLabel!.text!
println("\(tappedButtonTitle)ボタンがタップされました")
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
}