在Objective-C的早期,我们在UIAlertView
中使用了delegate:self,这样我们就可以在index ...中调用buttonclicked等方法,但现在在swift中我在哪里设置该委托?因为我的按钮点击索引方法没有被调用..
import UIKit
class ViewController:UIViewController,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
let cell :UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: nil)
cell.text = "HI \(indexPath.row)"
cell.detailTextLabel.text = "SWIFT"
return cell
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
return 5
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)
{
var alert = UIAlertController(title: "Demo", message: "You have selected row number\(indexPath.row)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
alert.addAction(UIAlertAction(title: "KILL", style: UIAlertActionStyle.Destructive, handler: nil))
alert.addAction(UIAlertAction(title: "PUNE", style: UIAlertActionStyle.Default, handler: nil))
alert.addAction(UIAlertAction(title: "Mumbai", style: UIAlertActionStyle.Default, handler: nil))
alert.addAction(UIAlertAction(title: "Kolkata", style: UIAlertActionStyle.Default, handler: nil))
alert.addAction(UIAlertAction(title: "Chennai", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func demoFunction (myName:NSString)
{
NSLog("%@", "swapnil")
}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int)
{
NSLog("%@", "YOU PRESSED OK" )
switch (buttonIndex)
{
case 0:NSLog("%@", "YOU PRESSED OK" )
case 1:NSLog("%@", "YOU PRESSED KILLER" )
case 2:NSLog("%@", "YOU PRESSED PUNE" )
case 3:NSLog("%@", "YOU PRESSED MUMBAI" )
case 4:NSLog("%@", "YOU PRESSED KOLKATA" )
case 5:NSLog("%@", "YOU PRESSED Chennai" )
default :NSLog("%@", "You have pressed default")
}
}
}
答案 0 :(得分:2)
您不应该使用委托方法,实际上UIAlertController
不提供委派。
在您的情况下,您的警报措施应该是这样的:
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {(alert :UIAlertAction!) in
println("YOU PRESSED OK")
}))
以及每个动作等等!
答案 1 :(得分:1)
UIAlertController
未实现委托属性。它使用-addAction:
的handler参数来处理按钮上的点击。以下是如何完成此操作的示例:
alert.addAction(UIAlertAction(title: "RandomTitle", style: UIAlertActionStyle.Default, handler:{(alert :UIAlertAction!) -> void in
//Handle action here.
//You can also use the alert title property to differentiate between
//UIAlertActions and hand the same closure in to each one. E.i.
if(action.title == "first option"){
//handle when the user taps the "first option" button.
}
}))