【问题标题】:How to add action to a programmatically-made button?如何向以编程方式制作的按钮添加操作?
【发布时间】:2018-01-24 01:30:14
【问题描述】:

由于我在通过情节提要创建按钮时遇到问题,我开始通过代码启动右侧导航栏按钮 - 通过这个问题 How can I go back to the initial view controller in Swift? 找到。此代码旨在将我带回我的根视图控制器。

这是目前的代码。

 let button1 = UIBarButtonItem(image: UIImage(named: "HomeM25.png"), style: .plain, target: self, action: #selector(getter: UIDynamicBehavior.action))
    self.navigationItem.rightBarButtonItem  = button1

    func button() {
        self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
    }

我的印象是,如果我要改变

action: #selector(getter: action)

我可以像这样在这个按钮初始化之后创建一个函数

func action() {
        self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
    }

但是,我收到了“在声明之前使用局部变量'action'”。我不明白为什么这种解释不会执行/为什么当它唯一的用途是函数名时我必须建立动作变量?任何帮助将不胜感激。

更新 1:当前代码

  override func viewDidLoad() {
    super.viewDidLoad()

    let button1 = UIBarButtonItem(image: UIImage(named: "HomeM25.png"), style: .plain, target: self, action: #selector(action))
    self.navigationItem.rightBarButtonItem  = button1

    func action() {
        self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
    }

更新 1:还必须使用不同的功能操作才能返回到原始视图控制器。

    self.navigationController!.popToRootViewController(animated: true)

【问题讨论】:

    标签: swift function button action


    【解决方案1】:

    应该是#selector(action)。您可以在函数中定义函数。将action 移出viewDidLoad 函数。尝试这个。

    override func viewDidLoad() {
        super.viewDidLoad()
        let button1 = UIBarButtonItem(image: UIImage(named: "HomeM25.png"), style: .plain, target: self, action: #selector(action))
        self.navigationItem.rightBarButtonItem  = button1
    }
    
    
    func action() {
        self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
    }
    

    【讨论】:

    • 您应该在viewDidLoad 函数或任何其他函数中执行此操作。发布完整代码。
    猜你喜欢
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多