開発メモ

開発関係のメモをいろいろと。たぶん。

ボタンをViewControllerに接続

動作を確認した環境

環境 情報
Xcode 6.3.2 (6D2105)
iOS 8.3
Swift 1.2
Date 2015/6/5

ボタンをViewControllerに接続

ツールバーに配置したボタンが押された時、プログラムから処理ができるように、アクションを接続しておく。

Main.storyboardを開いてる画面で、アシスタントエディターを開いて接続先のクラスを表示。

アシスタントエディターを開くのは画面右上のボタンで、切り替えるのがわかりやすいかな? Option + Command + Returnのショートカットは、意外と使わない。

f:id:see_ku:20150605093455p:plain

Document Outlineからアクションを設定したいボタンを探して、アシスタントエディターのクラスへ、Ctrlを押したままでDrag&Drop

f:id:see_ku:20150605093506p:plain

もちろん、Document Outlineを使わないで、スクリーン上のオブジェクトからDrag&Dropしても同じことが出来る。・・・Xcodeでアプリを開発する上で、一番便利でわかりにくいのがこの操作じゃないかな?

元になるパーツと接続先のクラスで特に問題がなければ、接続の設定を行うViewが表示される。

f:id:see_ku:20150605093519p:plain

今回は、ボタンを押された時に処理を行いたいのでConnectionをActionに変更。関数名にonRepeatを入力して、[Connect]を実行。

同じ要領で全てのボタンを接続しておく。今回の様に同じような接続を複数作成する場合、あらかじめ、接続先の関数を準備しておいて、Drag&Dropで接続だけするのが楽かも?

ついでに、動作確認用のprintln()を組み込んで、ViewControllerはこんな感じに。

class ViewController: UIViewController {

    @IBAction func onRepeat(sender: AnyObject) {
        println(__FUNCTION__)
    }

    @IBAction func onPrev(sender: AnyObject) {
        println(__FUNCTION__)
    }

    @IBAction func onPause(sender: AnyObject) {
        println(__FUNCTION__)
    }

    @IBAction func onPlay(sender: AnyObject) {
        println(__FUNCTION__)
    }

    @IBAction func onNext(sender: AnyObject) {
        println(__FUNCTION__)
    }

    @IBAction func onShuffle(sender: AnyObject) {
        println(__FUNCTION__)
    }

    ////////////////////////////////////////////////////////////////

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

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

}

コンパイル&実行して、正常に接続が出来てるか、確認しておく。

https://itunes.apple.com/jp/app/four-album-shuffle-arubamu/id866046150?mt=8&uo=4&at=10l8JW&ct=hatenablog