获得点击UILabel的价值

时间:2016-01-18 04:15:20

标签: ios swift uilabel

所以我目前正在创建动态标签,我需要在点击时获取它们的价值。我用for循环创建了1到10的标签。然后我将它们与UITapGestureRecognizer一起添加到视图中以检测何时点击。我需要做的是获取tapped标签的文本。因此,如果我点击带有1文字的标签,我希望返回1。这是我正在做的创建标签和添加手势识别器。

   for number in numbers.characters {
       let touch = UITapGestureRecognizer(target:self, action: "numberClicked")
       touch.numberOfTapsRequired = 1

       let label = UILabel(frame: CGRectMake(CGFloat(x), CGFloat(y1), CGFloat(width), CGFloat(height)))
       label.font = label.font.fontWithSize(38)
       label.text = String(number)
       label.userInteractionEnabled = true
       label.addGestureRecognizer(touch)
       self.view.addSubview(label)
   }

1 个答案:

答案 0 :(得分:1)

以下是在动作函数中获取标签文本的示例。关键更改是在tap操作的名称中添加冒号,表示它采用sender参数。然后,您可以访问发件人的view属性以获取UILabel本身。

for number in numbers.characters {
    // add a colon after "numberClicked" to indicate it takes an argument
    let touch = UITapGestureRecognizer(target:self, action: "numberClicked:")
    touch.numberOfTapsRequired = 1

    let label = UILabel(frame: CGRectMake(CGFloat(x), CGFloat(y1), CGFloat(width), CGFloat(height)))
    label.font = label.font.fontWithSize(38)
    label.text = String(number)
    label.userInteractionEnabled = true
    label.addGestureRecognizer(touch)
    self.view.addSubview(label)
 }


func numberClicked(gesture: UIGestureRecognizer) {
    if gesture.state == .Ended {
        if let theLabel = (gesture.view as? UILabel)?.text {
            print(theLabel) // print the "1"
        }
    }
}