如何向UIAlertController添加操作并获取操作结果(Swift)

时间:2016-06-26 18:51:46

标签: ios xcode swift uialertcontroller

我想设置一个带有四个动作按钮的UIAlertController,以及要设置为“心形”,“黑桃”,“钻石”和“球杆”的按钮标题。按下按钮时,我想返回其标题。

简而言之,这是我的计划:

// 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

2 个答案:

答案 0 :(得分:34)

试试这个:

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)

并在此处理行动:

func doSomething(action: UIAlertAction) {
    //Use action.title
}

为了将来参考,您应该查看Apple's Documentation on UIAlertControllers

答案 1 :(得分:14)

这是一个带有两个动作加上和ok-action的示例代码:

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)")
}}
与i.E. handler:myHandler 你定义一个函数,来读取结果 让printSomething

这只是一种方式; - )

有问题吗?