美文网首页
swift UIAlertController使用带输入框示例讲

swift UIAlertController使用带输入框示例讲

作者: 小緈福 | 来源:发表于2018-07-20 10:54 被阅读0次

    swift UIAlertController用于弹出对话框消息,这里将介绍UIAlertController输入框案例的实现方法,使用比较简单,首先我们创建两个UIButton按钮,给button按钮添加点击事件,如图。

    在ViewController.swift中实现这两个点击事件,代码如下。

    import UIKit

    class ViewController: UIViewController {

        override func viewDidLoad() {

            super.viewDidLoad()       

        }

        //弹出普通提示框

        @IBAction func clickDelBtn(_ sender: UIButton) {

            let alertController = UIAlertController.init(title: "提示", message: "数据删除成功", preferredStyle:.alert)

            let cancel = UIAlertAction.init(title: "好的", style: UIAlertActionStyle.cancel) { (action:UIAlertAction) ->() in

                print("处理完成\(action)")

            }

            alertController.addAction(cancel);

            self.present(alertController, animated: true, completion: nil)

        }

        //弹出带有输入框的提示框

        @IBAction func clickInputBtn(_ sender: UIButton) {

            //初始化UITextField

            var inputText:UITextField = UITextField();        

            let msgAlertCtr = UIAlertController.init(title: "提示", message: "请输入用户名", preferredStyle: .alert)       

            let ok = UIAlertAction.init(title: "确定", style:.default) { (action:UIAlertAction) ->() in         

                if((inputText.text) == ""){

                    print("你输入的是:\(String(describing: inputText.text))")

                }

            }

            let cancel = UIAlertAction.init(title: "取消", style:.cancel) { (action:UIAlertAction) -> ()in

                print("取消输入")

            }

            msgAlertCtr.addAction(ok)

            msgAlertCtr.addAction(cancel)

            //添加textField输入框

            msgAlertCtr.addTextField { (textField) in

                //设置传入的textField为初始化UITextField

                inputText = textField

                inputText.placeholder = "输入数据"

            }

            //设置到当前视图

            self.present(msgAlertCtr, animated: true, completion: nil)

        }

    }

    UIAlertController运行之后效果分别如图所示。

    对着swift案例练习一遍吧!

    相关文章

      网友评论

          本文标题:swift UIAlertController使用带输入框示例讲

          本文链接:https://www.haomeiwen.com/subject/cgyfmftx.html