gpt4 book ai didi

ios - 从 UIBarButtonItem 触发 textFieldShouldReturn

转载 作者:行者123 更新时间:2023-11-28 10:48:54 24 4
gpt4 key购买 nike

我正在尝试添加触发我的 textFieldShouldReturnUIBarButtonItem,但我收到此错误:

Argument of '#selector' does not refer to an '@objc' method, property, or initializer

UIBarButtonItem

func addToolBar(textField: UITextField) {
let toolBar = UIToolbar()
toolBar.barStyle = .default
let doneButton = UIBarButtonItem(
title: "Done",
style: .done,
target: self,
action: #selector(textFieldShouldReturn(textField))) //** ERROR **
toolBar.isUserInteractionEnabled = true
toolBar.sizeToFit()
textField.inputAccessoryView = toolBar
}

textFieldShouldReturn:

@objc func textFieldShouldReturn(_ textField: UITextField) {
print("hi there!")
}

错误表明我应该需要将 objc 添加到我的 textFieldShouldReturn,但我已经有了。我也已经尝试过以下方法:

有谁知道我可以如何设置我的 UIBarButtonItem 来触发我的 textFieldShouldReturn

最佳答案

这里有几个问题。

  1. textFieldShouldReturn 方法是UITextFieldDelegate 的委托(delegate)方法。它只能由 UITextField 调用。它有一个参数 - 文本字段。
  2. UIBarButtonItem 目标/选择器需要是一种特定于处理按下的按钮的方法。选择器需要具有两个可能的签名之一。这可以是一个没有参数的方法,也可以是一个带有一个参数的方法,该参数将是触发事件的 UIBarButtonItem
  3. 您正在尝试调用不匹配的 UITextFieldDelegate 方法作为您的 UIBarButtonItem 的选择器。那根本行不通。

如果您希望文本字段委托(delegate)和按钮选择器都执行相同的操作,则让两个相应的方法中的每一个都调用第三个通用方法。

func textFieldShouldReturn(_ textField: UITextField) {
processReturn()
}

@objc func barButtonAction(_ button: UIBarButtonItem) {
processReturn()
}

func processReturn() {
// Do whatever is needed
}

并设置条形按钮项目:

let doneButton = UIBarButtonItem(
title: "Done",
style: .done,
target: self,
action: #selector(barButtonAction)

如果您的 processReturn 方法需要对文本字段的引用,请添加该参数。诀窍是从 barButtonAction 方法获取对文本字段的引用。它不能作为参数传递给该方法,因此您需要有一个引用文本字段的属性。

关于ios - 从 UIBarButtonItem 触发 textFieldShouldReturn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47066912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com