LoginSignup
0
1

More than 3 years have passed since last update.

Swiftの文について見ていきます

Posted at

概要

新たにSwiftを学び始めたので、アウトプットも兼ねて、Xcodeの文を見ていきます。

viewController.swift
class ViewController: UIViewController {
    @IBOutlet weak var countLabel: UILabel!
    var count = 0 
    override func viewDidLoad() {
        super.viewDidLoad()
        countLabel.text = "0" 
    }
    @IBAction func plus(_ sender: Any) {
        count = count + 1     
        countLabel.text = String(count)
        if(count >= 10){
            changeTextColor()
        }
    }
    @IBAction func minus(_ sender: Any) {
        count = count - 1
        countLabel.text = String(count)
        if(count <= 0){
            resetColor()
        }
    }
    func changeTextColor(){
        countLabel.textColor = .yellow
    }
    func resetColor(){
        countLabel.textColor = .white
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var countLabel: UILabel!
    var count = 0 

この部分は変数の宣言になります。varとつけて宣言を表明し、その後にcountLabelという変数名をつけています。その後のcount変数を宣言して 0 を代入しています。

    override func viewDidLoad() {
        super.viewDidLoad()
        countLabel.text = "0" 
    }

この部分はアプリを開いた時に自動的に読み込まれる箇所です。
countLabelにオブジェクト.textをつけてそれに文字型の0を代入して表示しています。

    @IBAction func plus(_ sender: Any) {
        count = count + 1     
        countLabel.text = String(count)
        if(count >= 10){
            changeTextColor()
        }
    }

この部分はボタンがタッチされた時該当する plusメソッドが動きますが、その処理を記述しています。
countに1を足す処理です。そしてさらに足したcountを文字型に変えて表示しています。
その後のif文はcountが10超えたらchageTextColorというメソッドを読み込むという記述です。

    @IBAction func minus(_ sender: Any) {
        count = count - 1
        countLabel.text = String(count)
        if(count <= 0){
            resetColor()
        }
    }

ここはさっきと逆でcountから1引く処理をしています。そしてそれを文字型に変えて表示。if文で0以下になったらresetColorというメソッドが読み込まれるという記述です。

    func changeTextColor(){
        countLabel.textColor = .yellow
    }
    func resetColor(){
        countLabel.textColor = .white
    }

最後にこの箇所はメソッドを定義する箇所です。
changeTextColorメソッドでは.textColorオブジェクトを使って文字を黄色に変えています。
resetColorメソッドは同じように文字を白色に変えています。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1