我遇到了一个奇怪的问题,也许只是缺乏关于Swift 3.0 / iOS 10的知识,所以希望你可以引导我走向正确的方向或向我解释我做错了什么。
目前的工作方式
我正在尝试使用样式.alert创建一个UIAlertController,这样我就可以为我的应用程序获取用户文本输入。我的要求是文本不能为空,如果之前有文本,则必须是不同的。
我可以使用以下代码来实现我想要的目标:
//This function gets called by a UIAlertController of style .actionSheet
func renameDevice(action: UIAlertAction) {
//The AlertController
let alertController = UIAlertController(title: "Enter Name",
message: "Please enter the new name for this device.",
preferredStyle: .alert)
//The cancel button
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
//The confirm button. Make sure to deactivate on first start
let confirmAction = UIAlertAction(title: "Ok", style: .default, handler: { action in
self.renameDevice(newName: alertController.textFields?.first?.text)
})
//Configure the user input UITextField
alertController.addTextField { textField in
log.debug("Setting up AlertDialog target")
textField.placeholder = "Enter Name"
textField.text = self.device.getName()
textField.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
}
//Disable the OK button so that the user first has to change the text
confirmAction.isEnabled = false
self.confirmAction = confirmAction
//Add the actions to the AlertController
alertController.addAction(cancelAction)
alertController.addAction(confirmAction)
present(alertController, animated: true, completion: nil)
}
var confirmAction: UIAlertAction?
func textFieldDidChange(_ textField: UITextField){
log.debug("IT CHAGNED!=!=!=!=!")
if let text = textField.text {
if !text.isEmpty && text != self.device.getName() {
confirmAction?.isEnabled = true
return
}
}
confirmAction?.isEnabled = false
}
//Finally this code gets executed if the OK button was pressed
func renameDevice(newName: String?){ ... }
我希望如何工作
到目前为止一直很好,但我会要求用户在各个地方输入文本,所以我想使用实用程序类来处理所有这些东西。最后的电话会是这样的:
func renameDevice(action: UIAlertAction) {
MyPopUp().presentTextDialog(title: "Enter Name",
message: "Please enter the new name for this device.",
placeholder: "New Name",
previousText: self.device.getName(),
confirmButton: "Rename",
cancelButton: "Cancel",
viewController: self){ input: String in
//do something with the input, e. g. call self.renameDevice(newName: input)
}
我用什么
所以我在这个小课程中实现了所有内容:
class MyPopUp: NSObject {
var confirmAction: UIAlertAction!
var previousText: String?
var textField: UITextField?
func presentTextDialog(title: String, message: String?, placeholder: String?, previousText: String?, confirmButton: String, cancelButton: String, viewController: UIViewController, handler: ((String?) -> Swift.Void)? = nil) {
//The AlertController
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
//The cancel button
let cancelAction = UIAlertAction(title: cancelButton, style: .cancel)
//The confirm button. Make sure to deactivate on first start
confirmAction = UIAlertAction(title: confirmButton, style: .default, handler: { action in
handler?(alertController.textFields?.first?.text)
})
//Configure the user input UITextField
alertController.addTextField { textField in
log.debug("Setting up AlertDialog target")
self.textField = textField
}
//Set placeholder if necessary
if let placeholder = placeholder {
self.textField?.placeholder = placeholder
}
//Set original text if necessary
if let previousText = previousText {
self.textField?.text = previousText
}
//Set the target for our textfield
self.textField?.addTarget(self, action: #selector(textChanged), for: .editingChanged)
log.debug("It appears that our textfield \(self.textField) has targets: \(self.textField?.allTargets)")
//Store the original text for a later comparison with the new entered text
self.previousText = previousText
//Disable the OK button so that the user first has to change the text
confirmAction.isEnabled = false
//Add the actions to the AlertController
alertController.addAction(cancelAction)
alertController.addAction(confirmAction)
viewController.present(alertController, animated: true, completion: nil)
}
func textChanged() {
if let text = textField?.text {
if !text.isEmpty && text != previousText {
confirmAction.isEnabled = true
return
}
}
confirmAction.isEnabled = false
}
}
问题
我的问题是,无论我在哪里尝试为UIAlertController的UITextField设置目标,它都不会执行我的目标。我尝试在alertController.addTextField {}中设置TextFields委托以及在那里设置目标。最让我困惑的问题是设置占位符和原始文本的工作正常但是从不调用委托或目标函数。为什么在UIViewController中执行时相同的代码有效,但在实用程序类中执行时却无效?
解决方案(更新)
显然我犯了一个错误。在我的viewcontroller中,我创建了一个MyPopUp实例并在其上调用present()函数。
MyPopUp().presentTextDialog(title: "Enter Name",
message: "Please enter the new name for this device.",
placeholder: "New Name",
previousText: self.device.getName(),
confirmButton: "Rename",
cancelButton: "Cancel",
viewController: self)
在presentTextDialog()中,我认为将MyPopUp的当前实例设置为委托/目标就足够了,但似乎MyPopUp实例立即被释放,因此从未调用过。我非常简单的解决方法是在实例变量中创建MyPopUp实例,并在需要时调用present方法。
let popup = MyPopUp()
func renameDevice(action: UIAlertAction) {
popup.presentTextDialog(...){ userinput in
renameDevice(newName: userinput)
}
}
答案 0 :(得分:1)
好的,这就是我做错了。
我创建了一个实用工具类,我必须实例化
班级本身基本上是空的,唯一的目的是成为UITextField的目标或代表
我实例化了这个类并立即调用了演示函数而没有保留参考
通过不保留对我的实例的引用,该对象必须在我的viewcontroller中呈现UIAlertController后立即释放。
解决方案:只需在viewcontroller中保留一个引用即可。当然一个局部变量不会做。我将引用存储在我的viewcontroller的实例变量中,但这并不是非常“快速”#34;。我还是一个快速的初学者,也许我的思想已经被损坏了#34;通过其他语言(java,c#)。我可能首先将我的实用程序类设为单例或为UIViewController创建扩展以显示警报。如果您有其他好的想法,请随时教他们:)
答案 1 :(得分:0)
而不是在NSObject类中呈现对话。您必须使用委托和协议来提供警报。用这个替换你的代码。在View Controller中,我们有一个名为renameDevice的函数。你可以在这里提出警告。
<强> MyPopUp.swift 强>
import UIKit
class MyPopUp: NSObject {
var confirmAction: UIAlertAction!
var previousText: String?
var textField: UITextField?
var delegate : MyPopUpDelegate!
func textChanged() {
if let text = textField?.text {
if !text.isEmpty && text != previousText {
confirmAction.isEnabled = true
return
}
}
confirmAction.isEnabled = false
}
}
protocol MyPopUpDelegate {
func renameDevice(action: UIAlertAction)
}
<强> ViewController.swift 强>
import UIKit
class ViewController: UIViewController,MyPopUpDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func renameDevice(action: UIAlertAction) {
// Add dialogue that you wnat to create.
}
}
答案 2 :(得分:0)
首先,在MyPopUp
课程中,您需要遵守UITextFieldDelegate
这样的方法
class MyPopUp:NSObject,UITextFieldDelegate {
然后在添加你的UITextField时提醒你需要像这样设置委托给那个UITextField
alertController.addTextField { textField in
log.debug("Setting up AlertDialog target")
textField.delegate = self
self.textField = textField
}
然后你需要实现UITextField Delegate方法来获取你的UITextField中的变化
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
这将解决您的问题。另请检查this