整数の変数を使ってみよう
var count = 0 // countという名前で変数を作成 count += 1 // カウントを1上げる
文字列と整数をつなげる
countLabel.text = "残り\(100-count)回"
文字列は「”」(ダブルクオーテーションマーク)で囲みます。
文字列の中に計算式や変数などを入れる場合には「\(ここに変数など)」と記載します。
こちらも同じ意味です。StringとIntはつなげることができないので「100-count」を「String(100-count)」としてStringに変換しています。
countLabel.text = "残り"+String(100-count)+"回"
復習しよう StringやIntとは
if-else文を使ってみよう
var battery = 20 if battery < 20 { // バッテリーが20未満の時 } else if battery < 50 { // バッテリーが20以上50未満の時 } else { // バッテリーが50以上の時 }
完成したコード
import UIKit class ViewController: UIViewController { @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var eggButton: UIButton! var count = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func onEgg(_ sender: Any) { count += 1 countLabel.text = "残り\(100-count)回" var newImage:UIImage! if count < 10 { newImage = UIImage(named: "egg1") } else if count < 50 { newImage = UIImage(named: "egg2") } else if count < 100 { newImage = UIImage(named: "egg3") } else { newImage = UIImage(named: "egg4") } eggButton.imageView?.image = newImage } }
コメント