LoginSignup
0
1

More than 3 years have passed since last update.

3日目:UITextFieldキーボードをニョキっと配置、リアルタイムに計算するアプリ

Posted at

3日目のアプリ

UITextFieldキーボードをニョキっと配置、リアルタイムに計算するアプリ

画面キャプチャ

以下の流れで作りました。

  1. storyboadに1つのUITextFieldと、2つLabelを配置
  2. ボタンを端末が変わってもレイアウトが崩れないように設定
  3. 上記要素をViewController.swiftへoptionドラッグして紐付ける
  4. 紐付けができたら、ViewController.swiftでコードを書く

できたこと

  • UITextFieldの配置ができるようになった
  • デバイスサイズが変わってもレイアウトが崩れないように設定できた
  • テキスト入力エリア毎にソフトウェアキーボードを変更して表示できるようになった
  • 文字入力したものを配列に格納することができるようになった
  • 文字を入力すると、リアルタイムに計算結果を出力することができるようになった
  • UITextField内がキーボードのデリートキーで空欄になった時の処理を入れることができた ##書いたコードを共有します!
import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var beanWeight: UITextField!
    @IBOutlet weak var amountWater: UILabel!
    @IBOutlet weak var time: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        beanWeight.placeholder = "豆の量を入力してください" //ステークホルダー
        self.beanWeight.keyboardType = .numberPad //キーボードタイプ

        beanWeight.delegate = self

        beanWeight.addTarget(self, action: #selector(getWeight(textField:)), for: UIControl.Event.editingChanged) //何か入力があったら呼び出す


    }

    @objc func getWeight(textField: UITextField) {

        var changeInt:Double = 0.0
        var calWater:Double = 0.0
        var calTime:Double = 0.0

        if  beanWeight.text!.isEmpty {  //豆の量が空になったら処理
            changeInt = 0
            calWater = 0
            calTime = 0
               beanWeight.text = ""
               amountWater.text = String(calWater)
               time.text = String(calTime)
               beanWeight.endEditing(true)
        } else {  //豆の量を入力されたら処理
            changeInt = Double(beanWeight.text!)!
               calWater = changeInt * 180.0 / 10.0
               calTime = changeInt / 10.0 * 4.0 * 60.0
           amountWater.text = String(calWater)
               time.text = String(calTime)
        }
}
}

感想

3日目。Qiitaに記事をアップしたつもりで下書きになっていた。。

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