532

私は Swift で UIAlertView を作成するために取り組んできましたが、何らかの理由で次のエラーが発生しているため、ステートメントを正しく取得できません。

指定された引数を受け入れる「init」のオーバーロードが見つかりませんでした

これが私が書いた方法です:

let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
                     delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)

それを呼び出すには、次を使用しています:

button2Alert.show()

現在のところクラッシュしており、構文を正しく理解できないようです。

4

36 に答える 36

964

UIAlertViewクラスより:

// UIAlertView は非推奨です。代わりに、preferredStyle の UIAlertControllerStyleAlert でUIAlertControllerを使用してください

iOS 8 では、次のことができます。

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

現在は、 iOS 8 でs およびsUIAlertControllerとして知られているものを作成して操作するための単一のクラスです。UIAlertViewUIActionSheet

編集:アクションを処理するには:

alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
    switch action.style{
    case .Default:
        print("default")
        
    case .Cancel:
        print("cancel")
        
    case .Destructive:
        print("destructive")
    }
}}))

Swift 3の編集:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)

Swift 4.x の編集:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
    switch action.style{
        case .default:
        print("default")
        
        case .cancel:
        print("cancel")
        
        case .destructive:
        print("destructive")
        
    }
}))
self.present(alert, animated: true, completion: nil)
于 2014-06-03T18:48:41.560 に答える
116

標準コンストラクターを使用して UIAlert を作成できますが、「レガシー」コンストラクターは機能しないようです。

let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
于 2014-06-03T18:52:13.370 に答える
12

Swift 2 のプロトコル拡張により、View Controller にデフォルトの実装を提供するプロトコルを作成できます。

ShowsAlert.swift

import UIKit

protocol ShowsAlert {}

extension ShowsAlert where Self: UIViewController {
    func showAlert(title: String = "Error", message: String) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
        presentViewController(alertController, animated: true, completion: nil)
    }
}

ViewController.swift

class ViewController: UIViewController, ShowsAlert {
    override func viewDidLoad() {
        super.viewDidLoad()
        showAlert(message: "Hey there, I am an error message!")
    }
}
于 2015-10-07T13:33:54.220 に答える
11

コンストラクターで otherButtonTitles を提供しないでください。

let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")

alertView.show()

しかし、私は Oscar に同意します。このクラスは iOS 8 で廃止されるため、iOS 8 のみのアプリを実行している場合、UIAlertView は使用されません。それ以外の場合は、上記のコードが機能します。

于 2014-12-22T14:51:07.827 に答える
11

UIAlertView を迅速な言語で表示する:-

プロトコル UIAlertViewDelegate

let alert = UIAlertView(title: "alertView", message: "This is alertView", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles: "Done", "Delete")
alert.show()

UIAlertViewController を迅速な言語で表示します:-

let alert = UIAlertController(title: "Error", message: "Enter data in Text fields", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
于 2014-09-03T12:53:11.193 に答える
9

こいつを見つけた、

var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();

良くはありませんが、うまくいきます:)

アップデート:

しかし、ヘッダーファイルで次のように見つけました:

extension UIAlertView {
    convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}

誰かがこれを説明できるかもしれません。

于 2014-06-03T19:05:20.460 に答える
5

スイフト3

以下は、Swift 3 でボタン 1 つでシンプルなアラートを作成する方法の簡単な例です。

let alert = UIAlertController(title: "Title",
                              message: "Message",
                              preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)

上記の例では、アクションのハンドル コールバックが省略されています。これは、ボタンが 1 つあるアラート ビューのデフォルトの動作は、ボタンがクリックされると消えるためです。

「alert.addAction(action)」でアラートに追加できる別のアクションを作成する方法を次に示します。さまざまなスタイルは、.default、.destructive、.cancel です。

let action = UIAlertAction(title: "Ok", style: .default) { action in
    // Handle when button is clicked    
}
于 2016-09-28T12:52:43.793 に答える
5
    class Preview: UIViewController , UIAlertViewDelegate
    {
        @IBAction func MoreBtnClicked(sender: AnyObject)
        {
            var moreAlert=UIAlertView(title: "Photo", message: "", delegate: self, cancelButtonTitle: "No Thanks!", otherButtonTitles: "Save Image", "Email", "Facebook", "Whatsapp" )
            moreAlert.show()
            moreAlert.tag=111;
        }

        func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int)
        {
            if alertView.tag==111
            {
                if buttonIndex==0
                {
                    println("No Thanks!")
                }
                else if buttonIndex==1
                {
                    println("Save Image")
                }
                else if buttonIndex == 2
                {
                    println("Email")
                }
                else if buttonIndex == 3
                {
                    println("Facebook")
                }
                else if buttonIndex == 4
                {
                    println("Whatsapp")
                }
            }
        }
    }
于 2015-07-10T12:35:47.710 に答える
5

これをアプリのどこからでも便利に使用できるようにするために、シングルトン クラスを作成しました: https://github.com/Swinny1989/Swift-Popups

次に、次のように複数のボタンを含むポップアップを作成できます。

Popups.SharedInstance.ShowAlert(self, title: "Title goes here", message: "Messages goes here", buttons: ["button one" , "button two"]) { (buttonPressed) -> Void in
    if buttonPressed == "button one" { 
      //Code here
    } else if buttonPressed == "button two" {
        // Code here
    }
}

または、次のような 1 つのボタンでポップアップします。

Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")
于 2015-10-26T09:31:58.953 に答える
5

私には別のトリックがあります。ログアウト アラートが適用される 5 つのクラスがあるとします。迅速なクラス拡張を試してください。

ファイル - 新規 - Swift クラス - 名前を付けます。

以下を追加します。

public extension UIViewController
{

    func makeLogOutAlert()
    {
        var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)

        refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
            self.navigationController?.popToRootViewControllerAnimated(true)
        }))

        refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
            refreshAlert .dismissViewControllerAnimated(true, completion: nil)
        }))

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

実装: self.makeLogOutAlert()。それが役に立てば幸い。

于 2015-09-17T13:48:42.337 に答える
4

エラーなしでコンパイルするための次のUIAlertView初期化コードを取得しました (最後の可変引数部分はおそらくトリッキーだと思います)。selfしかし、 (デリゲートとして渡している)クラスがUIAlertViewDelegateコンパイル エラーを解消するためのプロトコルを採用していることを確認する必要がありました。

let alertView = UIAlertView(
                  title: "My Title",
                  message: "My Message",
                  delegate: self,
                  cancelButtonTitle: "Cancel",
                  otherButtonTitles: "OK"
                )

ちなみに、これは私が得ていたエラーです(Xcode 6.4の時点で):

タイプ '(title: String, message: String, delegate: MyViewController, cancelButtonTitle: String, otherButtonTitles: String)' の引数リストを受け入れるタイプ 'UIAlertView' の初期化子が見つかりません

他の人が述べたように、iOS 8.x+ をターゲットにできる場合は、UIAlertController に移行する必要があります。iOS 7 をサポートするには、上記のコードを使用します (iOS 6 は Swift でサポートされていません)。

于 2015-07-14T07:44:33.497 に答える
3

SWIFT 4 : 次のように UIViewController の拡張機能を作成するだけです。

extension  UIViewController {        
    func showSuccessAlert(withTitle title: String, andMessage message:String) {
        let alert = UIAlertController(title: title, message: message,
                                  preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "OK".localized, style:
        UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
}

ViewController で、UIViewController によって提供されているかのように、上記の関数を直接呼び出します。

    yourViewController.showSuccessAlert(withTitle: 
      "YourTitle", andMessage: "YourCustomTitle")
于 2018-06-03T13:37:48.363 に答える
1

古い方法: UIAlertView

let alertView = UIAlertView(title: "Default Style", message: "A standard alert.", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alertView.alertViewStyle = .Default
alertView.show()

// MARK: UIAlertViewDelegate

 func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
 switch buttonIndex {

    // ...
   }
  }

新しい方法: UIAlertController

let alertController = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .Alert)

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
 }
 alertController.addAction(cancelAction)

 let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
 }
 alertController.addAction(OKAction)
 self.presentViewController(alertController, animated: true) {
 // ...
}
于 2016-07-04T08:43:26.967 に答える
1

Swift での面白い例を次に示します。

private func presentRandomJoke() {
  if let randomJoke: String = jokesController.randomJoke() {
    let alertController: UIAlertController = UIAlertController(title:nil, message:randomJoke, preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title:"Done", style:UIAlertActionStyle.Default, handler:nil))
    presentViewController(alertController, animated:true, completion:nil)
  }
}
于 2015-04-25T06:51:27.790 に答える
1

以下は、アラート ビューとアクション シートの再利用可能なコードです。アプリケーションのどこにでもアラートを表示するには、1 行を記述します。

class AlertView{

    static func show(title:String? = nil,message:String?,preferredStyle: UIAlertControllerStyle = .alert,buttons:[String] = ["Ok"],completionHandler:@escaping (String)->Void){
        let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)

        for button in buttons{

            var style = UIAlertActionStyle.default
            let buttonText = button.lowercased().replacingOccurrences(of: " ", with: "")
            if buttonText == "cancel"{
                style = .cancel
            }
            let action = UIAlertAction(title: button, style: style) { (_) in
                completionHandler(button)
            }
            alert.addAction(action)
        }

        DispatchQueue.main.async {
            if let app = UIApplication.shared.delegate as? AppDelegate, let rootViewController = app.window?.rootViewController {
                rootViewController.present(alert, animated: true, completion: nil)
            }

        }
    }
}

使用法 :

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        AlertView.show(title: "Alert", message: "Are you sure ?", preferredStyle: .alert, buttons: ["Yes","No"]) { (button) in
            print(button)
        }
    }

}
于 2018-08-15T11:01:09.177 に答える
1

// UIAlertView のカスタム クラス

//MARK:- MODULES
import Foundation
import UIKit

//MARK:- CLASS
class Alert  : NSObject{

static let shared = Alert()

var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?

/** show */
public func show(title : String?, message : String?, viewController : UIViewController?, okAction : AlertSuccess = nil) {

    let version : NSString = UIDevice.current.systemVersion as NSString
    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
        alert?.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in

            if let okAction = okAction {
                okAction()
            }
        }))
        viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil);
    }
}

/** showWithCancelAndOk */
public func showWithCancelAndOk(title : String, okTitle : String, cancelTitle : String, message : String, viewController : UIViewController?, okAction : AlertSuccess = nil, cancelAction : AlertSuccess = nil) {
    let version:NSString = UIDevice.current.systemVersion as NSString;

    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: title, message: message, preferredStyle:.alert)

        alert?.addAction(UIAlertAction(title: cancelTitle, style: .default, handler: { (action: UIAlertAction) in

            if let cancelAction = cancelAction {
                cancelAction()
            }
        }))
        alert?.addAction(UIAlertAction(title: okTitle, style: .default, handler: { (action: UIAlertAction) in

            if let okAction = okAction {
                okAction()
            }
        }))
        viewController?.present(alert!, animated:true, completion:nil);
    }
}

/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {

    let version : NSString = UIDevice.current.systemVersion as NSString
    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
        viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
        let when = DispatchTime.now() + 1
        DispatchQueue.main.asyncAfter(deadline: when){
            self.alert?.dismiss(animated: true, completion: nil)
        }
    }
}
}

使用する:-

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self) //without ok action

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
                            //ok action
                        }) // with ok action

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
                            //ok action 
}, cancelAction: {
 //cancel action
}) //with cancel and ok action

Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self) //with timer
于 2018-02-28T13:24:52.257 に答える