2014-10-11 33 views
0

我對swift和iOS開發一般都陌生,所以我在Xcode中做了一個Action Sheet,但現在我想從Action Sheet中執行操作。我很熟悉在ObjC中通過使用按鈕索引來做到這一點,但我似乎無法迅速解決這個問題。Swift中的ActionSheet操作

我還想定製我的動作表使文本顏色不同,但這並不重要。請讓我知道你是否可以幫忙。由於

這是到目前爲止我的代碼,但我當按鈕被按下的行動.TAG部分是錯誤的...

@IBAction func ActionSheet(sender: UIButton) { 

    var sheet: UIActionSheet = UIActionSheet(); 
    let title: String = "Action Sheet!"; 
    sheet.title = title; 
    sheet.addButtonWithTitle("Cancel"); 
    sheet.addButtonWithTitle("A course"); 
    sheet.addButtonWithTitle("B course"); 
    sheet.addButtonWithTitle("C course"); 
    sheet.cancelButtonIndex = 0; 
    sheet.showInView(self.view); 

} 


func actionSheet(sheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) { 
    if (actionSheet.tag == 1) { 
     NameLabel.text = "I am confused" 

    } 
} 
+0

所以,被ü能夠解決這個問題? – bllakjakk 2014-10-12 17:16:06

+0

還沒有,但我希望很快 – 2014-10-13 02:09:09

+0

我想通了......我只是忘記了2行代碼 – 2014-10-13 21:39:41

回答

1

您需要:

  1. 讓你視圖控制器符合UIActionSheetDelegate協議:

    class ViewController: UIViewController, UIActionSheetDelegate {

  2. 添加self作爲委託,並設置標籤,以1:

    var sheet: UIActionSheet = UIActionSheet() 
    let title: String = "Action Sheet!" 
    sheet.title = title 
    sheet.addButtonWithTitle("Cancel") 
    sheet.addButtonWithTitle("A course") 
    sheet.addButtonWithTitle("B course") 
    sheet.addButtonWithTitle("C course") 
    sheet.cancelButtonIndex = 0 
    sheet.delegate = self     // new line here 
    sheet.tag = 1       // another new line here 
    sheet.showInView(self.view) 
    
  3. 現在你可以使用buttonIndex


func actionSheet(sheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) { 
    if sheet.tag == 1 { 
     println(buttonIndex) 
     println(sheet.buttonTitleAtIndex(buttonIndex)) 
    } 
} 
+0

他必須確保他的actionSheet的標籤實際上也是1(它不是基於他的代碼設置的)。 – 2014-10-11 19:38:12

+0

是的,我擺脫了我的代碼版本中的標籤,但沒有發佈我的版本。 – vacawama 2014-10-11 19:41:41

+0

即使包含UIActinoSheetDelegate,這仍然不適用於我...它有一個錯誤,表示:'(UIActionSheet!,clickedButtonAtIndex:Int) - >()'沒有名爲'tag'的成員。任何想法如何我可以解決這個問題? – 2014-10-12 00:07:54

0

我覺得你的序列是不正確的,代表也沒有設置。

聲明你的類爲代表

class ViewController: UIViewController, UIActionSheetDelegate{ 

...

定義動作片

@IBAction func ActionSheet(sender: UIButton) { 

    let actionSheet = UIActionSheet(title: "ActionSheet", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Done", otherButtonTitles: "A Course", "B Course", "C course") 
    actionSheet.showInView(self.view) 

} 

定義委託功能

func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) 
{ 
    switch buttonIndex{ 

    case 0: 
     NSLog("Done"); 
     break; 
    case 1: 
     NSLog("Cancel"); 
     break; 
    case 2: 
     NSLog("A Course"); 
     break; 
    case 3: 
     NSLog("B Course"); 
     break; 
    case 4: 
     NSLog("C Course"); 
     break; 

}