gpt4 book ai didi

swift - UIBarButtonItem 选择器不工作

转载 作者:搜寻专家 更新时间:2023-11-01 05:55:04 26 4
gpt4 key购买 nike

我在导航 Controller 中嵌入了一个 MainViewController,如下所示:
enter image description here

在 MainViewController.swift 中,我以编程方式添加了两个 UIBarButtonItem(左和右):

class MainViewController: UIViewController {

let rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(onRightClick))
let leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(onLeftClick))

override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = rightButton
navigationItem.leftBarButtonItem = leftButton
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

@objc func onRightClick() {
print("[Main] Right Click")
}

@objc func onLeftClick() {
print("[Main] Left Click")
}
}

按钮确实显示在屏幕上,但有趣的是,选择器函数 onLeftClickonRightClick 永远不会在我按下左键或右键时被调用。有什么我应该做的才能让它发挥作用吗?我正在使用 Xcode 9.3。

最佳答案

尝试一次内部作用域

override func viewDidLoad() {
super.viewDidLoad()

let rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(self.onRightLeftClick(_ :)))
rightButton.tag = 1
let leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(self.onRightLeftClick(_ :)))
rightButton.tag = 2
self.navigationItem.rightBarButtonItem = rightButton
self.navigationItem.leftBarButtonItem = leftButton
}

将 Action 处理为

func onRightLeftClick(_ sender: UIBarButtonItem){
if sender.tag == 1{
// rightButton action
}else{
// leftButton action
}
}

关于swift - UIBarButtonItem 选择器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50834375/

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