簡體   English   中英

有關實現UIButton擴展的問題

[英]Issue with implementation of Extension of UIButton

我在多個VC中有一個通話按鈕,可以執行對相同號碼進行通話的操作。 我沒有在每個VC中定義相同的功能,而是決定創建UIButton的擴展。

需要幫助,不確定為什么我會遇到問題,但是在target:self出現錯誤target:selfExpected parameter type following ':'

以下是代碼:-

extension UIButton {
    func callBtn(target:self)
    {
        let url = NSURL(string: "tel://1234567890")!
        UIApplication.sharedApplication().openURL(url)
    }
}

編輯:更新為提到的解決方案:-

extension UIButton {
    func callBtn(target:UIButton)
    {
        let url = NSURL(string: "tel://1234567890)")!
        UIApplication.sharedApplication().openURL(url)
    }
}

內部必需的VC :-(調用如下)

callBtn.addTarget(self, action: #selector(callBtn.callBtn(_:)), forControlEvents: .TouchUpInside)

出現以下錯誤:-

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '- unrecognized selector sent to instance 0x15e8b330 '

您的代碼應該像

extension UIButton {
func callBtn(target:UIButton)
{
    let url = NSURL(string: "tel://1234567890")!
    UIApplication.sharedApplication().openURL(url)
}
}

如果您要查看錯誤,則表明無法識別的選擇器已發送到實例。 這是因為應該在target上調用您在按鈕的addTarget:方法中添加的“操作”。 在這里,您給出的是self ,它是UIViewController類型的對象,並且沒有名為callBtn:的方法。 因此,它將無法識別callBtn:方法調用。 而是將擴展名從UIButton更改為UIViewController ,以實現該方法。 因此,每當點擊按鈕時,它將在目標selfUIViewController )上調用您的操作方法( callBtn:

extension UIViewController {
    func callBtn(sender: UIButton) {
        let url = NSURL(string: "tell://1234567890")!
    }
}

嘗試使用..

  extension UIButton {
        func callBtn(target:UIButton)
        {
            let url = NSURL(string: "tel://1234567890")!
            UIApplication.sharedApplication().openURL(url)
        }
    }

您仍然需要任何幫助隨時問我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM