iPadとPlaygroundsで学ぶ:「ボタン」と「イベント」
ユーザーの入力に対して何か処理する機能で一番簡単なものはボタンだと思います。
今回はボタン(UIButton)を使って基本的なイベント処理をやってみます。
仕様
mapの上にボタンを配置し、ボタンを押したら予め決めてある座標へ移動するアプリを作ります。
コード
前回のコードにボタンを追加します。 以下コードです。
import UIKit import MapKit class ViewController: UIViewController { // ボタンのイベントから操作するためメンバ変数にしておく fileprivate var map: MKMapView? override func loadView() { super.loadView() self.map = MKMapView(frame: UIScreen.main.bounds) if let map = self.map { self.view = map } let button = UIButton(frame: CGRect(x:100, y:100, width:50, height:50)) // ボタンにイベントを設定する button.addTarget(self, action:#selector(buttonEvent(_:)), for:UIControl.Event.touchUpInside) // ボタンの背景色を赤にする button.backgroundColor = UIColor.red // サブビューとして追加する(ビューの上に配置する) self.view.addSubview(button) } // ボタンを押した時の処理 //マップの中心座標を北緯35度、東経135に変更 // funcの前に@objcが必要 @objc func buttonEvent(_ sender: UIButton) { self.map!.centerCoordinate = CLLocationCoordinate2D(latitude: 35.0, longitude:135.0) } } import PlaygroundSupport PlaygroundPage.current.liveView = ViewController()
適当にマップを動かしてからボタン(赤い四角)を押すと北緯35.0°東経135.0°に移動します。
説明
MKMapView
マップを提供するビューです。MapKitに含まれます。
UIButton.addTarget
親クラスUIControl
がもつメソッドでイベント処理を設定するために使用します。
https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget
self
action
が呼ばれるコントロールを指定します。action
イベント発生時に呼ばれる関数を指定します。controlEvents
どのイベントが発生した時action
を呼ぶかを指定します。
action
に指定する関数のタイプは
https://developer.apple.com/documentation/uikit/uicontrol#1943645
のListing.1に書かれています。
今回の例では下記の関数です。
@objc func buttonEvent(_ sender: UIButton) { self.map!.centerCoordinate = CLLocationCoordinate2D(latitude: 35.0, longitude:135.0) }
マップで中心に表示する座標MapKit.centerCoordinate
にCLLocationCoordinate
で北緯35.0°東経135.0°を設定しています。
@objc
はお約束として書くようです。
iPadとPlaygroundsで学ぶ:の前のiOSアプリ開発準備
XCodeで開発したいけどMac持ってない、プログラミングのコツを掴めたらMacを買いたい、という方は多いのではないでしょうか。
そういう方にオススメなのがiPadのPlaygroundsアプリです。
お手軽にコーディング出来て直ぐに試せる良い環境ですので是非試して下さい。
iPadだけで勉強できる
iPadだけです。他に必要なものはありません。 私は2018年のiPad Pro 11インチ 64GBとキーボードを使っています。
開発アプリはPlaygroundsだけ
swift Playgroundsを使います。 App Storeからダウンロードするだけです。
プログラミング開始手順
プログラミング開始手順は以下です。
- Playgroundsを起動します
- 空白のテンプレートを入手します
- 空白のテンプレートにコードを入力します
例えば、Mapを表示する機能を試したい場合は下記のように記述するだけです。
import UIKit import MapKit class ViewController: UIViewController { override func loadView() { super.loadView() let map = MKMapView(frame: UIScreen.main.bounds) self.view = map } } import PlaygroundSupport PlaygroundPage.current.liveView = ViewController()
“コードを実行する”を押すとこのように表示され、操作を試すことができます。
この調子で色々試せます。