How to call initWith… in swift

2020-04-20 14:24发布

I have a an objective-c class (RDAlertView) which create an Alert (UIAlertView for ios < 8 and UIAlertController for ios >=8 )

Here is the code in Objective-C:

RDAlertView* alert = [[RDAlertView alloc] initWithTitle:@"Notification" 
                                                message:@"message" 
                                             completion:completion:^(NSInteger buttonIndex, NSInteger cancelButtonIndex, NSArray *textflieds) { } 
                                      cancelButtonTitle:@"Ok" 
                                      otherButtonTitles:nil];

[alert show];

My question is: How to call this in Swift without any change in my class (if possible)?

Here is a link for the sample project : https://bitbucket.org/ejanowski/rdalertview-issue

4条回答
家丑人穷心不美
2楼-- · 2020-04-20 14:33

These methods are treated like constructors. You can call them like this:

var alert = RDAlertView("notification", message:"message", completion:nil, cancelButtonTitle:"Cancel", otherButtonTitles:nil)
alert.show()

Caveat: written without an IDE, careful of syntax errors / typos

查看更多
手持菜刀,她持情操
3楼-- · 2020-04-20 14:37

I think this is what you need:

var alert = RDAlertView(title: "Notification", message: "message", completion: nil, cancelButtonTitle: "OK", otherButtonTitles: nil)
alert.show()

Hope It will help.

查看更多
走好不送
4楼-- · 2020-04-20 14:44
UIAlertView.showWithTitle("Hello", message: "Hello World", cancelButtonTitle: "Okay") { alertView, buttonIndex in

// Do something when the alert view is clicked

let anAlertView = UIAlertView(title: "Choice", message: "Pick one", cancelButtonTitle: "No", otherButtonTitles: "Yes", "Maybe")

anAlertView.showWithCompletion { alertView, buttonIndex in

switch buttonIndex
{
   case 1: println("Yes")
   case 2: println("Maybe")
   default: println("No")
}
}
查看更多
我想做一个坏孩纸
5楼-- · 2020-04-20 14:51

UIAlertView is deprecated in iOS 8.

You can show an alert with this code:

var alert = UIAlertController(title: "Alert", message: "test", preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))

self.presentViewController(alert, animated: true, completion: nil)
查看更多
登录 后发表回答