当我触摸任何按钮时,我的应用程序崩溃了

时间:2018-04-05 10:03:38

标签: ios swift

如何在Utility Class中使用选择器并定义?我的代码创建了一些错误。请告诉我如何解决此错误?

错误:当我触摸任何按钮时,我的应用程序崩溃了。

class BarButton{
    static func items(navigationItem: UINavigationItem) {
        //Hide Back Button
        navigationItem.hidesBackButton = true

        //Add Label to Left of NavigationBar
        let leftLabel = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
        leftLabel.tintColor = UIColor.init(red: 30/255, green: 104/255, blue: 140/255, alpha: 1)
        navigationItem.setLeftBarButton(leftLabel, animated: false)

        //List Button
        let btnList = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 22))
        btnList.setImage(UIImage(named:"list-icn"), for: .normal)
        btnList.addTarget(self, action: #selector(listBtn), for: .touchUpInside)
        let rightBarBtn1 = UIBarButtonItem.init(customView: btnList)
        rightBarBtn1.tintColor = UIColor(red: 30/255, green: 104/255, blue: 140/255, alpha: 1)

        //Notification Button
        let btnList2 = UIButton(frame: CGRect(x: 0, y: 0, width: 22, height: 22))
        btnList2.setImage(UIImage(named:"notification-icn"), for: .normal)
        btnList2.addTarget(self, action: #selector(notificationBtn), for: .touchUpInside)
        let rightBarBtn2 = UIBarButtonItem.init(customView: btnList2)
        rightBarBtn2.tintColor = UIColor(red: 30/255, green: 104/255, blue: 140/255, alpha: 1)
        navigationItem.setRightBarButtonItems([rightBarBtn1, rightBarBtn2], animated: true)
    }

    @objc func listBtn() {
        print("List Btn")
    }

    @objc func notificationBtn() {
        print("Notification Btn")
    }
}

2 个答案:

答案 0 :(得分:1)

试试这个,看看:

let btnList = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 22))
btnList.setImage(UIImage(named:"list-icn"), for: .normal)

// Update selector
btnList.addTarget(self, action: #selector(BarButton.listBtn(sender:)), for: .touchUpInside)
let rightBarBtn1 = UIBarButtonItem.init(customView: btnList)
rightBarBtn1.tintColor = UIColor(red: 30/255, green: 104/255, blue: 140/255, alpha: 1)


//Notification Button
let btnList2 = UIButton(frame: CGRect(x: 0, y: 0, width: 22, height: 22))
btnList2.setImage(UIImage(named:"notification-icn"), for: .normal)

// Update selector
btnList2.addTarget(self, action: #selector(BarButton.notificationBtn(sender:)), for: .touchUpInside)
let rightBarBtn2 = UIBarButtonItem.init(customView: btnList2)
rightBarBtn2.tintColor = UIColor(red: 30/255, green: 104/255, blue: 140/255, alpha: 1)
navigationItem.setRightBarButtonItems([rightBarBtn1, rightBarBtn2], animated: true)


// Try using static
@objc static func listBtn(sender: Any)
{
    print("List Btn")
}

// Try using static
@objc static func notificationBtn(sender: Any)
{
    print("Notification Btn")
}

答案 1 :(得分:0)

您的listBtnnotificationBtn方法是实例方法,但是您尝试在类上调用它们,而不是类实例 - 您的items方法是static,所以{ {1}}内部属于self类型。

要解决此问题,请将AnyObject.TypelistBtn方法设为静态。