0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

カウントアプリで型の変換,色の変更,if文,剰余について学ぶ

Last updated at Posted at 2020-04-21

この記事でわかる主なこと

1.Int型からString型への変換
2.テキストカラーの変更

解決できそうなエラー

Cannot assign value of type 'Int' to type 'String'

最終的にできるもの

1.Int型からString型への変換

画面に表示されるUILabelはString型しか扱うできない。しかし、四則演算を行えるのはInt型やdouble型であるので、それらの型で計算したものをUILabelに表示するにはInt型からString型への変換を行わなければならない。
Int型からString型への変換を以下のように行っている。


let convert = String(countNumber)

これで安心してUIlabelに数値を入れることができる。

2.テキストカラーの変更

アプリの中では数字が3で割り切れる時に**(変数)%3 == 0**のようにすることで3で割り切れることを表現している。
今回は数字が3で割り切れる時のみ色を変更しているので、


numberLabel.textColor = UIColor.yellow

を条件の中に入れれば良い。
さらに、条件を満たさなかった時には色を戻す必要があるので、


numberLabel.textColor = UIColor.white

を条件を満たさなかった時のelse文の中に書く必要がある。

全体のソースコード



import UIKit
class ViewController: UIViewController {
    var countNumber:Int = 0
    @IBOutlet weak var numberLabel: UILabel!
    @IBAction func downButton(_ sender: Any) {
        countNumber += 1
        let convert = String(countNumber)
        if countNumber % 3 == 0{
            numberLabel.text = convert
            numberLabel.textColor = UIColor.yellow
            print("\(countNumber)")
        } else {
            numberLabel.text = convert
             numberLabel.text = convert
            numberLabel.textColor = UIColor.white
        }
    }
    @IBAction func upButton(_ sender: Any) {
        countNumber -= 1
        let convert = String(countNumber)
        if countNumber % 3 == 0{
            numberLabel.textColor = UIColor.yellow
            numberLabel.text = convert
        } else {
            numberLabel.text = convert
            numberLabel.textColor = UIColor.white
        }
        
        numberLabel.text = convert
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        var convert = String(countNumber)
        numberLabel.text = convert
        numberLabel.textColor = UIColor.yellow
    }

}
GitHubURL

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?