LoginSignup
28
28

More than 5 years have passed since last update.

Swiftでラベルのタッチを検知する方法

Posted at

Objective-Cの例をSwiftで書く時に、downcastの所でしばらく悩んだので。

class ViewController: UIViewController {

    let TAG_LABEL1 = 1

    var label1: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.label1 = UILabel(frame: CGRectMake(0, 0, 100, 100))
        self.label1.text = "Foo"
        self.label1.layer.position = CGPoint(x: 100, y: 100)
        self.label1.userInteractionEnabled = true
        self.label1.tag = self.TAG_LABEL1
        self.view.addSubview(self.label1);

    }

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        super.touchesEnded(touches, withEvent: event)

        for touch: AnyObject in touches {
            var t: UITouch = touch as UITouch
            if t.view.tag == self.label1.tag {
                NSLog("Label touched")
            }
        }
    }

}
28
28
0

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
28
28