UIButtonをタップした時にfuncをcallする
細々とSwiftでアプリ実装を進めててるけど、ググるとObjective-CとSwiftのサンプルが出てくる事が多い。 結果として、Swiftを学びつつもObjective-Cが少しずつ読める(読む気になる)という感じになってきた。
さて、ちょっとハマったのでメモ。
UIButtonをコードから生成して、funcをcallする方法。 UIButtonからcallする場合はsenderを定義する必要がある。
作ったボタンをタップするとException発生
unrecognized selector sent to instance 0x7ff630592d80'
対応
- callするfuncの引数にsender: AnyObjectを追加
原因
- callされる側にSender
サンプル
let hogeBtn = UIButton(frame: CGRectMake(0, 0, 300, 50)) hogeBtn.layer.position = CGPoint(x: self.view.frame.width/2, y:100) hogeBtn.setTitle("hogeButton", forState: .Normal) hogeBtn.addTarget(self, action: "hoge:", forControlEvents: .TouchUpInside) self.view.addSubview(hogeBtn) // NG パターン func hoge() { NSLog("called") } // OK パターン func hoge(sender: AnyObject) { NSLog("called") } // OK パターン 必ずUIButtonからcallされるのでAnyObjectじゃなくて良い func hoge(sender: UIButton) { NSLog("called") }