LoginSignup
13
12

More than 5 years have passed since last update.

swiftでカスタムクラスを作ろう

Posted at

ViewControllerの中にごちゃごちゃ書くとプログラムが見にくくなるので、カスタムクラスを作る。
詳細! Objective-C iPhoneアプリ開発 入門ノート」のPart4 Chapter4-4学習記録です。

こんな感じになりました。
アプリ画像

学習の手引的なものは下記の感じです。

カスタムクラスを作ろう

  • カスタムクラスを作る
  • イニシャライザを作る
  • swiftクラスをXcodeのユーティリティから追加する
  • ペットの種類推薦アプリを作る
  • 乱数を発生させる。

ViewController.swift

class ViewController: UIViewController {

    // テキストボックス:名前
    @IBOutlet weak var MyTextBox: UITextField!

    // 提案動物名
    @IBOutlet weak var AnimalPlan: UILabel!

    // 提案カウンタ
    var counter: UInt8 = 0

    // 選択した動物
    @IBOutlet weak var ResultDisplay: UILabel!

    // 自作クラスのオブジェクトを作成
    var cu = CustomUtility()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        // 自作クラスの変数にアクセス
        self.cu.mywhere = "梅田"
    }

    // 送信ボタンを押す(名前を送信する)
    @IBAction func SendName(sender: UIButton) {
        // 挨拶文を作成
        var greet = self.cu.getGreet(self.MyTextBox.text)
        // コンソールに挨拶文をプリント
        print(greet)

    }

    // 提案を見る
    @IBAction func ShowPlan(sender: UIButton) {


        var plan = self.cu.getAnimalPlan()
        // 提案をラベルにセット
        self.AnimalPlan.text = plan
        if (self.counter > 2) {
            sender.enabled = false

        }

        self.counter++

    }

    // OKボタンを押す
    @IBAction func SelectAnimal(sender: UIButton) {
        self.ResultDisplay.text = self.AnimalPlan.text
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

CustomUtility.swift

class CustomUtility:NSObject {

    // 場所
    var mywhere:NSString = "大阪"

    // クラスを初期化
    override init() {
        println("初期化")
    }

    // 挨拶文を作成する
    func getGreet(who:NSString)-> NSString {
        var msg = " \(mywhere)\(who)さん、こんにちは "
        return msg
    }

    // 提案動物を作成
    func getAnimalPlan()-> NSString {
        // 提案配列
        var plans = ["ヨークシャテリア", "ウサギ", "カピバラ", "ニシキヘビ"]
        // 乱数作成
        var rnd = Int(arc4random()) % plans.count
        var plan = plans[rnd]
        return plan
    }
}

ここにソースを置いた。
https://github.com/hanoopy/ios_study1024


昨日も書いたけど、ストーリーボードに部品をいっぱい置いて
適当に放置してると、実行時エラーになることがある。
メッセージ:「terminating uncaught exception of type NSException」
エラー

原因がよくわからないけど、部品を追加する毎に実行していれば防げるかと。

13
12
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
13
12