30

テキスト フィールドと 2 つのボタン (CANCEL と SAVE) を持つ AlertController があります。これはコードです:

@IBAction func addTherapy(sender: AnyObject)
{
    let addAlertView = UIAlertController(title: "New Prescription", message: "Insert a name for this prescription", preferredStyle: UIAlertControllerStyle.Alert)

    addAlertView.addAction(UIAlertAction(title: "Cancel",
                                         style: UIAlertActionStyle.Default,
                                         handler: nil))

    addAlertView.addAction(UIAlertAction(title: "Save",
                                         style: UIAlertActionStyle.Default,
                                         handler: nil))

    addAlertView.addTextFieldWithConfigurationHandler({textField in textField.placeholder = "Title"})


    self.presentViewController(addAlertView, animated: true, completion: nil)


}

私がやりたいのは、NewAlbumを作成したいときにiOSの写真アプリケーションのように、テキストフィールドが空のときにSAVEボタンを無効にするためのチェックをテキストフィールドに実装することです。誰かが私に何をすべきか説明してください。

4

4 に答える 4

28

最初に、保存アクションを最初に無効にしてアラートコントローラーを作成します。次に、テキストフィールドを追加するときに通知を含めて、ハンドラーでその変更を監視し、そのセレクターで保存アクションを有効にするプロパティを切り替えるだけです。

これが私が言っていることです:

//hold this reference in your class
weak var AddAlertSaveAction: UIAlertAction?

@IBAction func addTherapy(sender : AnyObject) {

    //set up the alertcontroller
    let title = NSLocalizedString("New Prescription", comment: "")
    let message = NSLocalizedString("Insert a name for this prescription.", comment: "")
    let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
    let otherButtonTitle = NSLocalizedString("Save", comment: "")

    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)

    // Add the text field with handler
    alertController.addTextFieldWithConfigurationHandler { textField in
        //listen for changes
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTextFieldTextDidChangeNotification:", name: UITextFieldTextDidChangeNotification, object: textField)
    }


    func removeTextFieldObserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields[0])
    }

    // Create the actions.
    let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
        NSLog("Cancel Button Pressed")
        removeTextFieldObserver()
    }

    let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in
        NSLog("Save Button Pressed")
        removeTextFieldObserver()
    }

    // disable the 'save' button (otherAction) initially
    otherAction.enabled = false

    // save the other action to toggle the enabled/disabled state when the text changed.
    AddAlertSaveAction = otherAction

    // Add the actions.
    alertController.addAction(cancelAction)
    alertController.addAction(otherAction)

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

    //handler
func handleTextFieldTextDidChangeNotification(notification: NSNotification) {
    let textField = notification.object as UITextField

    // Enforce a minimum length of >= 1 for secure text alerts.
    AddAlertSaveAction!.enabled = textField.text.utf16count >= 1
}

私は別のプロジェクトでこれを行っています - このパターンはリンゴの例から直接得ました。UICatalog の例でこれらのパターンのいくつかを概説する非常に良いサンプル プロジェクトがあります: https://developer.apple.com/library/content/samplecode/UICatalog/Introduction/Intro.html

于 2014-06-29T14:07:33.873 に答える
3

@spoek提供のSwift 3.0更新ソリューション

func showAlert()
    {
        let titleStr = "title"
        let messageStr = "message"

        let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.alert)

        let placeholderStr =  "placeholder"

        alert.addTextField(configurationHandler: {(textField: UITextField) in
            textField.placeholder = placeholderStr
            textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingChanged)
        })

        let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (_) -> Void in

        })

        let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (_) -> Void in
            let textfield = alert.textFields!.first!

            //Do what you want with the textfield!
        })

        alert.addAction(cancel)
        alert.addAction(action)

        self.actionToEnable = action
        action.isEnabled = false
        self.present(alert, animated: true, completion: nil)
    }

    func textChanged(_ sender:UITextField) {
        self.actionToEnable?.isEnabled  = (sender.text! == "Validation")
    }
于 2016-11-04T08:54:00.297 に答える