【问题标题】:AlertController's code not acting rightAlertController 的代码不正确
【发布时间】:2016-01-29 02:18:19
【问题描述】:

我有一个警报弹出窗口,其中包含一个请求用户输入数据的文本字段。我终于得到了 textField 将数据投射到我需要的地方,但是我不能再保存该项目了。如果 alertAction 没有附加处理函数,我可以毫无问题地调用保存函数。现在我有了从文本字段中转换数据的“设置”操作,它将不再允许我调用该函数。它给出了“表达式解析为未使用的函数”的错误。而且,出于某种原因,它希望我拥有自我。在所有数据之前...见代码。

警报控制器:

@IBAction func saveButton(sender: AnyObject) {
    if (item?.slminqty == nil) {
    let alert = UIAlertController(title: "Minimun Qty", message: "Please set minimun Qty. for pantry.", preferredStyle: UIAlertControllerStyle.Alert)

        alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in
        textField.placeholder = "Minimun Qty."
        textField.keyboardType = .NumbersAndPunctuation
        textField.clearButtonMode = UITextFieldViewMode.WhileEditing
    }

    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: {saveitem}()))
    alert.addAction(UIAlertAction(title: "Set", style: UIAlertActionStyle.Default, handler: {(action) -> Void in
        let textField = alert.textFields![0].text!
        self.item?.slminqty = textField
        if self.item?.slminqty != nil{
        //if I place saveitem here it wants self.saveitem and gives error.
        }
        }))

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

    }else{

        if item != nil {
            edititems()
            print(item!.slminqty!)
        } else {
            createitems()
        }

        dismissVC()
    }
}

保存功能:

func saveitem(sender: AnyObject) {

    if item != nil {
        edititems()

    } else {
        createitems()
    }
    print(item?.slminqty)

    dismissVC()
}

显然,我这样做是非常困难的,或者总体上是错误的。如何将 textField 数据转换为 item.slminqty 并保存项目?

【问题讨论】:

  • 它需要 self ,因为您指的是块外的对象,块内的对象。如果这是有道理的。保留周期等等。 krakendev.io/blog/weak-and-unowned-references-in-swift
  • 你为什么要传递 textField,而不是 textField 中的文本? UIAlertController 应该在您关闭它时销毁,但您当前持有对其 textField 的引用。
  • @beau 是的,现在可以了。我没有想到。 @迈克尔这是我让它工作的唯一方法。 @vishnu 我已经尝试过了,它仍然会引发错误。
  • 你确定你有self.saveItem()和括号吗?如果您只有self.saveItem,您指的是saveItem 函数,而不是调用它。这将解释错误。但是你也不应该传递 textField ,否则可能会导致其他问题。
  • 是的。 self.saveitem() 给出错误“调用中参数#1 缺少参数”。至于 textField 而不是它的文本,我无法让它走另一种方式。它只会通过零。我已经尝试了几种不同的方法,但无法通过 alert.textfields![0].text 获得我必须得到的文本。我认为是文本。它正在传递我现在输入的内容并将其作为 item.slminqty。只是存钱的问题。如果有办法更好地做到这一点并且它有效,我绝对愿意接受。我只是在 swift 方面还不是很了解。

标签: ios iphone swift uialertcontroller


【解决方案1】:

是的,您必须使用自引用来调用保存项,因为两者具有不同的范围。您可能应该在里面使用self.saveitem()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多