如何获取UIButton ID?

时间:2016-01-20 16:56:43

标签: ios swift uibutton

我在Swift中动态创建了5个按钮,如下所示:

for theIndex in 0..<5 {

        let aButton = UIButton()
        aButton.frame = CGRectMake(self.view.bounds.width / 2 - 120, self.view.bounds.height / 2 - 150, 240, 300)
        aButton.setTitle("Button \(theIndex)", forState: .Normal)
        aButton.addTarget(self, action: "btnClicked:", forControlEvents:.TouchUpInside)

        self.view.addSubview(aButton) 
    }

但是如何为每个人获得 BUTTON_ID

 func btnClicked(sender: AnyObject?) {
        let vc = storyboard!.instantiateViewControllerWithIdentifier("vc_name") as! DetailVC
        vc.selectedId = **WANT_TO_PASS_BUTTON_ID_HERE**
        self.presentViewController(vc, animated:true, completion:nil)
    }

1 个答案:

答案 0 :(得分:2)

您可以使用按钮的tag属性(例如,您可以设置按钮的索引),稍后在func btnClicked(sender: AnyObject?)方法中检索它以确定按下索引的按钮

在循环索引时执行:

aButton.tag = theIndex

并在btnClicked方法中执行:

vc.selectedId = sender.tag

参见参考Apple docs on UIView