【问题标题】:UIBarButton action not workingUIBarButton 动作不起作用
【发布时间】:2016-05-16 12:35:10
【问题描述】:

我无法让一个简单的工具栏操作起作用 - 我以前见过这个问题,但答案似乎不起作用。到目前为止,我所做的只是创建了一个新的测试项目(使用 Xcode 7.3)并修改了 ViewController 类,如下所示:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print("viewDidLoad")

        let tb = UIToolbar()

        let actionClear = #selector(ViewController.clearAction(_:))
        let clearButton = UIBarButtonItem(barButtonSystemItem: .Trash, target: self, action: actionClear)
        tb.items = [clearButton]

        self.view.addSubview(tb)
        tb.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activateConstraints([
            tb.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor),
            tb.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor)
            ])
    }

    func clearAction (sender: AnyObject) {
        print("clear")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

代码编译没有错误,垃圾桶图标显示在屏幕底部(在 iPad 上测试),但当我触摸图标时,该操作永远不会执行。

我看到一些(旧的)答案似乎表明您需要使用带有 UIBarButtonItem 的自定义视图 (UIButton),但这似乎有点疯狂,因为 UIBarButtonItem 的目的是为工具栏创建一个项目。我在这里错过了什么?

【问题讨论】:

    标签: ios swift uibarbuttonitem


    【解决方案1】:

    这里的问题不在于您的 barButton,而是由于限制。 将宽度约束添加到您的工具栏:

    NSLayoutConstraint.activateConstraints([
                    tb.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor),
                    tb.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor),
                    tb.widthAnchor.constraintEqualToConstant(self.view.bounds.width)
                    ])
    

    【讨论】:

    • 谢谢,成功了!我没有怀疑约束有什么问题,因为垃圾桶确实出现在屏幕上,但它不是“活动的”。我想东西可以是可见的,但不是“可触摸的”?
    【解决方案2】:

    在 clearAction 方法中删除 sender:AnyObject 然后尝试 当您在选择器方法中使用空参数方法时

     func clearAction () {
            print("clear")
        }
    

    【讨论】:

    • 试过这个,但没有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    相关资源
    最近更新 更多