LoginSignup
4
6

More than 5 years have passed since last update.

コードのみでカウントアップアプリを作る

Last updated at Posted at 2018-05-07

はじめに

Swiftの学習をしようとした時にStoryboardを使ったサンプルはたくさんあるけど、コードのみでレイアウトを組むサンプルが少なかったので、これから少しづつ書いていきたいと思います。

なお筆者自身もiOS開発は初学者なので、温かい目で見守ってくださいm(_ _)m

環境

  • Swift4
  • xcode9.3

作るもの

とても単純なボタンを押したら、カウントアップやダウンが出来るというもの。
あくまでもコードのみでレイアウトを組むという演習なので、まずは簡単なものをささっとやってみたいと思います。

見た目の位置なんかも適当です

image.png

必要要件

  • ラベルの数字がボタン押下で変更される
  • Upボタンを押すと数字が+1される
  • Downボタンを押すと数字が-1される
  • 保存処理はしない

プロジェクトを作成

xcodeを開き、「single view application」でアプリを作成します。
プロジェクト名はなんでも良いのですが、今回は「countApp」としておきます。

実装

編集するファイルはAppDelegate.swiftViewController.swiftの2ファイルです。
どちらも初期状態で用意されているファイルなので、新規に作成する必要はありません。

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

  // 以下を追記
  self.window = UIWindow(frame: UIScreen.main.bounds)
  // 背景色を白に設定
  self.window?.backgroundColor = UIColor.white
  // ルートとなるコントローラーをViewControllerに設定
  self.window?.rootViewController = ViewController()
  self.window?.makeKeyAndVisible()

  return true
}

ViewController.swift

AppDelegate.swiftでベースのビューを作成したら、それ以外をViewController.swiftに記載します。

import UIKit

class ViewController: UIViewController {

  let label = UILabel()
  let rightBtn = UIButton()
  let leftBtn = UIButton()

  override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "CountApp"

    // viewの幅と高さを変数に格納
    let viewWidth = self.view.bounds.width
    let viewHeight = self.view.bounds.height

    // labelの座標を指定
    label.frame = CGRect(x: viewWidth / 4, y: viewHeight / 2 - 50, width: positionX / 2, height: 50)
    // 文字列で0を代入。UILabelは文字列しか格納出来ない
    label.text = "0"
    // 文字列をセンター寄せ
    label.textAlignment = .center
    // フォントサイズを30に
    label.font = UIFont.systemFont(ofSize: 30)
    // ビューに表示
    self.view.addSubview(label)

    // 右のボタンを座標指定
    rightBtn.frame = CGRect(x: viewWidth - 170, y: viewHeight / 2, width: 150, height: 150)
        // 背景色を青に
    rightBtn.backgroundColor = UIColor.blue
        // ボタンを丸く
    rightBtn.layer.cornerRadius = 75.0
    // ボタンに文字を追加
    rightBtn.setTitle("Up", for: .normal)
    // ボタンの文字の太さを変更
    rightBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 30)
        // @IBActionの代わりにaddTargetを使ってクリック時の処理を呼び出す
    rightBtn.addTarget(self, action: #selector(self.countUp), for: .touchUpInside)
    self.view.addSubview(rightBtn)

    leftBtn.frame = CGRect(x: 20, y: viewHeight / 2, width: 150, height: 150)
    leftBtn.backgroundColor = UIColor.red
    leftBtn.layer.cornerRadius = 75.0
    leftBtn.setTitle("Down", for: .normal)
    leftBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 30)
    leftBtn.addTarget(self, action: #selector(self.countDown), for: .touchUpInside)
    self.view.addSubview(leftBtn)

    }

    // プラス処理
    @objc func countUp(){
       let str = label.text!
       let num = Int(str)! + 1

       label.text = String(num)
    }

    // マイナス処理
    @objc func countDown(){
       let str = label.text!
       let num = Int(str)! - 1

       label.text = String(num)
    }
}

Storyboardであれば、@IBActionを使うのが一般的のようですが、コードベースはaddTargetを使います。

完成形はgithubを参照ください

以上です。

4
6
2

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
4
6