また1からこつこつと

最高はひとつじゃないと信じてまたがんばります。

SwiftでUIButtonを使う

※2016/10/31追記
この記事はSwift1.x時代に書いているので古いです

SwiftでUIButtonを使うときなかなか手こずったので書いておく。まあ普通の人はこんな間違えしないんだろうけど...

セレクターの部分に:を忘れる

コードを書いていざ実行!と思いシュミレータ立ち上げてボタンを押すとアプリが落ちる。エラーを見ると、Appdelegate.swiftの12行目って書いてあった。なにも触ってない状態だと12行名ってclassの宣言の部分だった。

こんなとこいじってないなーと思いつつよくよく見てみると...

let myButton:UIButton();
myButton.setTitle = "ぼくのぼたん"
myButton.addTarget(self, action: Selector("onClickMyButton"), forControlEvents: .TouchUpInside)

Selectorのところに:が抜けてた...
むむむってかんじですね

UILabelとの混同

これはなにかっていうとUIButtonをテキストのまま表示させておくときに、fontサイズとはをどうやってやるんだってこと
例えばUILabelだと、

let myLabel:UILabel = UILabel()
myLabel.text = "hoge"
myLabel.font = UIFont.systemFontOfSize(24)

みたいな書き方ができるわけです
でもUIButtonのテキスト部分にこうやると怒られる

なので、

let myButton:UIButton = UIButton()
myButton.setTitle = "ぼくのボタン"
myButton.titleLabel?.font = UIFont.systemFontOfSize(24)

ううむ。めんどくさかった。

複数のボタンからの処理を1つのfuncにまとめてあげる

これはたぶんデフォルトのやりかたなんだとおもいます。
いままで僕がなにをやっていたかというと、UIButtonが2つあるとしたら、

let firstButton:UIButton = UIButton()
firstButton.addTarget(self, action: Selector("firstFunc"), forControlEvents: .TouchUpInside)

let secondButton:UIButton = UIButton()
secondButton.addTarget (self, action: Selector("secondFunc"), forControlEvents: .TouchUpInside)

//途中省略

func firstFunc(sender: UIButton) {
  //処理
}

func secondFunc(sender: UIButton) {
  //処理
}

って書いてました。関数を2つつくってそれぞれで処理を分ける仕組み。
でもこれだと非効率的なので、switch文を使うのが一般的みたい。

let firstButton:UIButton = UIButton()
firstButton.addTarget(self, action: Selector("myFunc"), forControlEvents: .TouchUpInside)
firstButton.tag = 0

let secondButton:UIButton = UIButton()
secondButton.addTarget (self, action: Selector("myFunc"), forControlEvents: .TouchUpInside)
secondButton.tag = 1

//途中省略

func myFunc(sender: UIButton){
  switch sender.tag{
    case 0:
      //処理
    case 1:
      //処理
    default:
      //処理
    break
  }
}

なるほど。これで1つの送り先で複数の処理が可能なわけか!
最近Swiftやってるとすごく楽しいのでこれからも続けていきます!