我正在创建一个view controller,其中包含几个文本字段和一个确认用户输入的accept button。accept button还检查是否有任何文本字段为空。如果是这样的话,它将弹出一个alert,上面写着类似于it cannot be empty的内容。如果它不是空的,它将存储输入,然后跳转到另一个视图。
我创建了一个名为checEmpty()的独立函数,如下所示:
func checEmpty(title: String, object: UITextField) -> (Bool) {
if object.text.isEmpty {
let alertController = UIAlertController(title: "Invalid input",
message:"\(title) cannot be empty",
preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss",
style: UIAlertActionStyle.Default)
self.presentViewController(alertController, animated: true, completion: nil)
return false
} else {
return true
}
}我在acceptButton操作中调用这个函数:
@IBAction func acceptButton(sender: UIButton){
if(checEmpty("Event", object: eventName) && checEmpty("Priority", object: Priority)
{
//if not empty, confirm the user input
// ...
}当我运行它时,警报消息可以正常工作,但由于某种原因,控制台显示如下:
2015-08-03 12:11:50.656完成ItToday13777:688070>的窗口不等于视图的窗口!
有人能告诉我为什么会出现这个警告吗?非常感谢!
PS。我想要它做的是,如果任何文本字段是空的,显示警报,然后停留在同一个页面。如果没有一个是空的,那么执行segue并切换到另一个视图。除警告外,上述代码运行良好。
发布于 2015-08-03 05:16:19
这是您的工作代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var eventName: UITextField!
@IBOutlet weak var Priority: UITextField!
@IBAction func acceptButton(sender: UIButton){
if checEmpty("Event", object: eventName) && checEmpty("Priority", object: Priority){
println("Both Text Fields Are Empty")
}
}
func checEmpty(title: String, object: UITextField) -> (Bool) {
if object.text.isEmpty {
var Alert = UIAlertController(title: "Invalid input", message: "\(title) cannot be empty", preferredStyle: UIAlertControllerStyle.Alert)
Alert.addAction(UIAlertAction(title: "Dismiss", style: .Cancel, handler: { action in
println("Click of cancel button")
}))
self.presentViewController(Alert, animated: true, completion: nil)
return false
} else {
return true
}
}
}发布于 2015-08-03 05:12:46
使用此代码可用于“快速”中的警报视图控制器。可能对你有帮助。
import UIKit
protocol alertViewDelegate {
func actionActive(index:Int, tag:Int)
}
class AlertView: NSObject {
var delegate:alertViewDelegate!
func showAlert(title:String, message:String, actionName:NSArray, tag:Int) -> UIAlertController {
var alertController:UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
for str: AnyObject in actionName {
let alertAction:UIAlertAction = UIAlertAction(title: str as! String, style: UIAlertActionStyle.Default, handler: { (action) -> Void in
self.delegate.actionActive(actionName.indexOfObject(str), tag:tag)
})
alertController.addAction(alertAction)
}
return alertController;
}
}https://stackoverflow.com/questions/31779609
复制相似问题