2016-01-20 32 views
0

我已创建5个按钮动态斯威夫特这样的:如何获取UIButton ID?

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

考虑设置按钮的标签*或*将5个自定义按钮的数组存储在您的班级中。 – luk2302

回答

1

您可以用按钮(例如,你可以设置有一个按钮的指数)tag财产,后来在func btnClicked(sender: AnyObject?)方法检索它来确定与指数被推

,而骑自行车的按钮通过你的指标做:

aButton.tag = theIndex 

和方法做:

vc.selectedId = sender.tag 

参考参考Apple docs on UIView

+0

我是iOS新手。你能告诉我使用按钮标签吗? –

+0

@AsimKrishnaDas见我编辑的答案例如 – arrteme