LoginSignup
14
12

More than 5 years have passed since last update.

SwiftでUIButtonを動的に生成しクリックされたボタンを判別する方法

Last updated at Posted at 2015-04-01

SwiftでUIButtonを動的に生成しクリックされたボタンを判別する方法です。

UIButtonを継承したクラスを作って実現しています。
もっとスマートな方法があれば教えてほしいです。

ソース

ViewController.swift

import UIKit

class ViewController: UIViewController {

    // UIButtonを継承した独自クラス
    class MyButton: UIButton{
        let x:Int
        let y:Int
        init(x:Int,y:Int,frame:CGRect){
            self.x = x
            self.y = y
            super.init(frame:frame)
        }
        required init(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }

    //メイン
    override func viewDidLoad() {
        super.viewDidLoad()
        for x in 0...5{
            for y in 0...5{
            //位置を変えながらボタンを作る
                var btn : UIButton = MyButton(
                    x:x,
                    y:y,
                    frame:CGRectMake(CGFloat(x)*30,CGFloat(y)*30,20,20))
            //ボタンを押したときの動作
            btn.addTarget(self, action: "pushed:", forControlEvents: .TouchUpInside)
            //見える用に赤くした
            btn.backgroundColor = UIColor.redColor()
            //画面に追加
            view.addSubview(btn)
            }
        }
    }

    //ボタンが押されたときの動作
    func pushed(mybtn : MyButton){
        //押されたボタンごとに結果が異なる
        println("button at (\(mybtn.x),\(mybtn.y)) is pushed")
    }
}

実行結果

画面スナップショット

hoge.png

左上から右下に順番にボタンを押すと以下のようになる

button at (0,0) is pushed
button at (1,1) is pushed
button at (2,2) is pushed
button at (3,3) is pushed
button at (4,4) is pushed
button at (5,5) is pushed
14
12
2

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