【问题标题】:Call a function in viewController from an extension?从扩展调用 viewController 中的函数?
【发布时间】:2020-05-15 07:36:22
【问题描述】:

我正在使用此扩展程序来自定义我的键盘,并提供额外的选项。

    extension UITextField {

func addNumericAccessory(addPlusMinus: Bool) {
    let numberToolbar = UIToolbar()
    numberToolbar.barStyle = UIBarStyle.default

    var accessories : [UIBarButtonItem] = []

    if addPlusMinus {
        accessories.append(UIBarButtonItem(title: "+/-", style: UIBarButtonItem.Style.plain, target: self, action: #selector(plusMinusPressed)))
        accessories.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil))   //add padding after
    }

    accessories.append(UIBarButtonItem(title: "Clear", style: UIBarButtonItem.Style.plain, target: self, action: #selector(numberPadClear)))
    accessories.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil))   //add padding space
    accessories.append(UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(numberPadDone)))

    numberToolbar.items = accessories
    numberToolbar.sizeToFit()

    inputAccessoryView = numberToolbar
}

@objc func numberPadDone() {
    self.resignFirstResponder()
}

@objc func numberPadClear() {
    self.text = ""
}

@objc func plusMinusPressed() {
    guard let currentText = self.text else {
        return
    }
    if currentText.hasPrefix("-") {
        let offsetIndex = currentText.index(currentText.startIndex, offsetBy: 1)
        let substring = currentText[offsetIndex...]  //remove first character
        self.text = String(substring)
    }
    else {
        self.text = "-" + currentText
    }
}

}

如何让 numberPadDone 函数在我的 viewController 中调用函数?

我需要更新其他 TextFields,我无法在扩展中访问它们。有没有办法调用我的 viewController 中的 updateTextFields()?

编辑:

这个函数在我的viewController中 https://i.stack.imgur.com/O0kpS.png

从扩展调用函数 https://i.stack.imgur.com/aywzP.png

将 @objc func numberPadDone() 移动到 viewController https://i.stack.imgur.com/5di8d.png

总而言之,我需要这个扩展来为我的键盘添加减号,但还需要在我的 viewController 中调用函数。我遇到的问题是我无法访问我的 viewController 除了这个扩展是通过 self 的 TextField。

【问题讨论】:

  • 那么您面临什么问题?在控制器中访问它们有什么错误吗?
  • 它们应该可以访问
  • self.text 可访问,但脚本中的自定义函数无法识别。您在示例中看不到的是 self.updateTextFields(),它是我的 viewController 中的一个函数。我得到一个 updateTextField() 无法识别的错误。
  • 可以显示显示你的viewController吗?和错误屏幕截图?
  • 用截图更新了我的问题

标签: swift


【解决方案1】:

它们可以访问,但第一次自动完成可能无法正常工作。只需从 UITextField 调用 self.numberPadDonetext.numberPadDone,其中 text: UITextField 从 viewController 调用

【讨论】:

  • 我应该将 func numberPadDone 移动到我的视图控制器吗?因为目前它在扩展中。我想从中调用我自己的函数。
  • 这取决于您的任务。如果每个 UITextField 必须包含一些额外的功能 - 最好扩展 UITextField。如果您需要一次性计算某些东西 - 最好将其移动到代码的较高部分(UIViewContoler、Model、ViewModel 或任何其他,取决于选择的架构)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 2012-02-11
  • 2017-11-23
  • 1970-01-01
相关资源
最近更新 更多