Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active July 17, 2018 21:32
Show Gist options
  • Save KentarouKanno/9e5ee36fa3924b4f335b to your computer and use it in GitHub Desktop.
Save KentarouKanno/9e5ee36fa3924b4f335b to your computer and use it in GitHub Desktop.
UIAlertController

UIAlertController

★アラートを生成する

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

★アクションシートを生成する

let actionSheet: UIAlertController = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.ActionSheet)

★ UIAlertControllerStyle

UIAlertControllerStyle.Alert
UIAlertControllerStyle.ActionSheet

★ アラート/アクションシートに設定したタイトルを取得する

var title = alert.title

★ アラート/アクションシートに設定したメッセージを取得する

var message = alert.message

★ アラート/アクションシートに設定したUIAlertControllerStyleを取得する

var style = alert.preferredStyle

★キャンセルボタン(アクション)を生成する

let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
    (action: UIAlertAction!) -> Void in
    // ボタン押下時のイベントを記述
    print("Cancel")
})

★ Defaultボタン(アクション)を生成する

let defaultAction: UIAlertAction = UIAlertAction(title: "Default", style: UIAlertActionStyle.Default, handler: {
    (action: UIAlertAction!) -> Void in
    // ボタン押下時のイベントを記述
    print("Default")
})

★ 赤い文字のボタン(アクション)を生成する

let destructiveAction: UIAlertAction = UIAlertAction(title: "Destructive", style: UIAlertActionStyle.Destructive, handler: {
    (action: UIAlertAction!) -> Void in
    // ボタン押下時のイベントを記述
    print("Destructive")
})

★ UIAlertActionStyle

UIAlertActionStyle.Default
UIAlertActionStyle.Cancel
UIAlertActionStyle.Destructive

★ アラート、アクションシートにアクションを追加する

alert.addAction(cancelAction)
alert.addAction(defaultAction)
alert.addAction(destructiveAction)

★ アラートにテキストフィールドを表示する

// アラートのみに使用可能(複数追加可能)
alert.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in
            
})

★ アラートに追加するテキストフィールドをカスタム

alert.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in
            
    // プレイスフォルダを設定する
    text.placeholder = "placeholder"
            
    // セキュアなテキストフィールドを設定
    text.secureTextEntry = true

    // テキストフィールドにタグを設定
    text.tag = 5
})

★ ボタンを押下時テキストフィールドの文字列を取得する

let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> Void in
    
    // TextFieldから値を取得
    if let textFields = alert.textFields {
        for textField in textFields {
            print(textField.text)
        }
    }
})

★ アラート、アクションシートを表示する

presentViewController(alert, animated: true, completion: nil)

Template

★ UIAlertController Template

let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)

let action1 = UIAlertAction(title: "Action1", style: .default, handler: { action in
    print("Action1")
})

let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
    print("Cancel")
})

alert.addAction(action1)
alert.addAction(cancel)

present(alert, animated: true, completion: nil)
let alert = UIAlertController(title: "title", message: "message", preferredStyle: .Alert)

alert.addAction( UIAlertAction(title: "Action1", style: .Default, handler: { action in
    
    print("Action1")
}))

alert.addAction( UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
    
    print("Cancel")
}))

presentViewController(alert, animated: true, completion: nil)

★ UIAlertController Simple Template

let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
alert.addAction( UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)

★ UIAlertController ActionSheet

let alert = UIAlertController(title: "title", message: "message", preferredStyle: .actionSheet)
alert.addAction( UIAlertAction(title: "OK", style: .default, handler: nil))
alert.addAction( UIAlertAction(title: "NG", style: .default, handler: nil))
present(alert, animated: true, completion: nil)

★ UITextFieldを2つ使用して、両方に入力がない場合OKボタンが押せないサンプル

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    var okAction: UIAlertAction!
    var textFieldText1 = ""
    var textFieldText2 = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(100 * Double(NSEC_PER_MSEC)))
        dispatch_after(delayTime, dispatch_get_main_queue()) {
            self.searchBySearchBarText(textField)
        }
        return true
    }
    
    
    func searchBySearchBarText(textF: UITextField) {
        switch textF.tag {
        case 1: textFieldText1 = textF.text!
        case 2: textFieldText2 = textF.text!
        default: break
        }
        okAction.enabled =  textFieldText1.characters.count > 0 && textFieldText2.characters.count > 0 ? true : false
        
    }
    
    
    @IBAction func showAlert() {
        
        let alert = UIAlertController(title:"action",
                                      message: "alertView",
                                      preferredStyle: UIAlertControllerStyle.Alert)
        
        let cancelAction = UIAlertAction(title: "Cancel",
                                         style: UIAlertActionStyle.Cancel,
                                         handler:{
                                            (action:UIAlertAction!) -> Void in
                                            print("Cancel")
        })
        okAction = UIAlertAction(title: "OK",
                                          style: UIAlertActionStyle.Default,
                                          handler:{
                                            (action:UIAlertAction!) -> Void in
                                            print("OK")
        })
        
        okAction.enabled = false
        alert.addAction(cancelAction)
        alert.addAction(okAction)
        
        
        alert.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in
            text.delegate = self
            text.tag = 1
            text.placeholder = "first textField"
        })
        
        alert.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in
            text.delegate = self
            text.tag = 2
            text.placeholder = "second textField"
        })
        presentViewController(alert, animated: true, completion: nil)
    }
}

★ UITextFieldを2つ使用して(片方DatePickerの入ったInputView)、両方に入力がない場合OKボタンが押せないサンプル

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    var okAction: UIAlertAction!
    var textFieldText1 = ""
    var textFieldText2 = ""
    var pikerTextField: UITextField!
    let datePicker = UIDatePicker()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        datePicker.datePickerMode = .Date
        datePicker.addTarget(self, action: #selector(self.textFieldEditing(_:)), forControlEvents: UIControlEvents.ValueChanged)
        
    }
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(100 * Double(NSEC_PER_MSEC)))
        dispatch_after(delayTime, dispatch_get_main_queue()) {
            self.searchBySearchBarText(textField)
        }
        return true
    }
    
    
    func searchBySearchBarText(textF: UITextField) {
        switch textF.tag {
        case 1: textFieldText1 = textF.text!
        default: break
        }
        okAction.enabled =  textFieldText1.characters.count > 0 && textFieldText2.characters.count > 0 ? true : false
    }
    
    
    @IBAction func showAlert() {
        
        let alert = UIAlertController(title:"action",
                                      message: "alertView",
                                      preferredStyle: UIAlertControllerStyle.Alert)
        
        let cancelAction = UIAlertAction(title: "Cancel",
                                         style: UIAlertActionStyle.Cancel,
                                         handler:{
                                            (action:UIAlertAction!) -> Void in
                                            print("Cancel")
        })
        okAction = UIAlertAction(title: "OK",
                                          style: UIAlertActionStyle.Default,
                                          handler:{
                                            (action:UIAlertAction!) -> Void in
                                            print("OK")
        })
        
        okAction.enabled = false
        alert.addAction(cancelAction)
        alert.addAction(okAction)
        
        
        alert.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in
            text.delegate = self
            text.tag = 1
            text.placeholder = "first textField"
        })
        
        alert.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in
            text.delegate = self
            text.tag = 2
            text.placeholder = "second textField"
            self.pikerTextField = text
            text.inputView = self.datePicker
        })
        presentViewController(alert, animated: true, completion: nil)
    }
    
    
    func textFieldEditing(datePicker: UIDatePicker) {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy/MM/dd HH:mm"
        let dateStr = formatter.stringFromDate(datePicker.date)
        pikerTextField.text = dateStr
        textFieldText2 = dateStr
        searchBySearchBarText(UITextField())
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment