2016-01-20 107 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