UIBarButtonItem 选择器不起作用 [英] UIBarButtonItem selector not working

查看:43
本文介绍了UIBarButtonItem 选择器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在导航控制器中嵌入了一个 MainViewController,如下所示:

I have a MainViewController embed in a Navigation Controller, as shown below:

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

And in MainViewController.swift, I added two UIBarButtonItem(left and right) programmatically:

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.

The buttons did show on the screen, but the interesting thing is, the selector functions onLeftClick and onRightClick never get called whenever I pressed left or right button. Is there anything I should do to make it works? I am using Xcode 9.3.

推荐答案

尝试使用内部作用域一次

try with inside scope once

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
}

将动作处理为

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

这篇关于UIBarButtonItem 选择器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆