2016-06-26 7 views
6

UIAlertControllerに4つのアクションボタンを設定し、ボタンのタイトルを "hearts"、 "spades"、 "diamonds" 、および "クラブ"。ボタンが押されたら、そのタイトルを返したい。要するに UIAlertControllerにアクションを追加してアクションの結果を得る方法(Swift)

は、ここに私の計画である:

import UIKit 

// The UIAlertControllerStyle ActionSheet is used when there are more than one button. 
@IBAction func moreActionsButtonPressed(sender: UIButton) { 
    let otherAlert = UIAlertController(title: "Multiple Actions", message: "The alert has more than one action which means more than one button.", preferredStyle: UIAlertControllerStyle.ActionSheet) 

    let printSomething = UIAlertAction(title: "Print", style: UIAlertActionStyle.Default) { _ in 
     print("We can run a block of code.") 
    } 

    let callFunction = UIAlertAction(title: "Call Function", style: UIAlertActionStyle.Destructive, handler: myHandler) 

    let dismiss = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil) 

    // relate actions to controllers 
    otherAlert.addAction(printSomething) 
    otherAlert.addAction(callFunction) 
    otherAlert.addAction(dismiss) 

    presentViewController(otherAlert, animated: true, completion: nil) 
} 

func myHandler(alert: UIAlertAction){ 
    print("You tapped: \(alert.title)") 
} 

}

すなわちと:here's

// TODO: Create a new alert controller 

for i in ["hearts", "spades", "diamonds", "clubs"] { 

    // TODO: Add action button to alert controller 

    // TODO: Set title of button to i 

} 

// TODO: return currentTitle() of action button that was clicked 
+0

あなたの質問は何を見てみる必要がありますか?何を試しましたか、どのような問題がありましたか、そしてそれらの問題をデバッグしようとしたときに何を見つけましたか? – NobodyNada

答えて

10

二つの作用に加えて、[OK]アクションとサンプルハンドラ:myHandler の結果を読み取る関数を定義します。let printSomething

これは、任意の質問;-)

だけ方法は何ですか?

let alert = UIAlertController(title: "Alert Title", message: "Alert Message", style = .Alert) 
for i in ["hearts", "spades", "diamonds", "hearts"] { 
    alert.addAction(UIAlertAction(title: i, style: .Default, handler: doSomething) 
} 
self.presentViewController(alert, animated: true, completion: nil) 

をそしてここでアクションを扱う:

+0

ありがとう! presentViewControllerはアラートを表示しますか? –

+0

@Abhi Vはい、そうです! –

関連する問題