在掌握了提示框的使用后,可以向提示框中添加文本框,构成类似登录界面一样的弹出式提示登录窗口,注意仅限于提示框样式,下拉菜单样式不能使用
在上一篇文章(提示框的使用->UIAlertController)的基础上
1.使用UIAlertController里面的addTextFieldWithConfigurationHander方法就可以向提示框中添加文本框(个数不限)
在上一篇文章代码下添加以下代码
//添加文本框 alertController.addTextFieldWithConfigurationHandler{//闭包内是文本框属性配置,可以设置种属性,详情请参考UITextField类 (textField : UITextField!)->Void in//<span style="color:#ff0000;">注意Void 首字母大写</span> textField.placeholder = "用户名" } alertController.addTextFieldWithConfigurationHandler{ (textField : UITextField!)-> Void in textField.placeholder = "密码" textField.secureTextEntry = true//<span style="color:#ff6666;">影藏(安全文本)输入文本</span> }2.如何获取文本框内容了?
在创建"登录"按钮实例(我们将"确定"改为了"登录")时,加入闭包,进行获取值操作,当登录按钮响应时,会获取到值
你的代码应添加像如下代码
let alertAction2 = UIAlertAction(title: "登录", style: UIAlertActionStyle.Default ){ (action : UIAlertAction)->Void in var username = <span style="color:#ff6666;">(alertController.textFields?.first)! as UITextField//获取文本内容,并转换为U</span>ITextField var password = (alertController.textFields?.last)! as UITextField print(username) print(password) }
提示:文本框的更多属性请参看UITextField类,
因为CNDS暂时还未提供插入Swift代码 段,所以有的代码选择的是OB其实实际是Swift语言
完整代码(写在事件函数中)
@IBAction func testButon(sender: AnyObject) { //创建一个对话框实例 let alertController = UIAlertController(title: "欢迎使用我的软件", message: "你好", preferredStyle: UIAlertControllerStyle.Alert)//创建一个提示框的实例,并配置标题、信息、方式 //let alertAction = UIAlertAction(title: "重置", style: UIAlertActionStyle.Destructive, handler: nil )//创建一个提示框事件(类似自定生成按钮)的实例,并配置 //创建对话框事件按钮(防止一直在这里显示无法回到应用) let alertAction1 = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil ) let alertAction2 = UIAlertAction(title: "登录", style: UIAlertActionStyle.Default ){ (action : UIAlertAction)->Void in var username = (alertController.textFields?.first)! as UITextField//获取文本内容,并转换为UITextField var password = (alertController.textFields?.last)! as UITextField print(username) print(password) } //alertController.addAction(alertAction)//向提示框添加事件1 //添加文本框 alertController.addTextFieldWithConfigurationHandler{//闭包内是文本框属性配置 (textField : UITextField!)->Void in//注意Void 首字母大写 textField.placeholder = "用户名" } alertController.addTextFieldWithConfigurationHandler{ (textField : UITextField!)-> Void in textField.placeholder = "密码" textField.secureTextEntry = true//影藏(安全文本)输入文本 } //如何获取文本框的文本内容 //将事件按钮添加到对话框 alertController.addAction(alertAction2) alertController.addAction(alertAction1) self.presentViewController(alertController, animated: true, completion: nil )//显示提示框 }
}