2016-08-02 22 views
1

我創建了我自己的框架,並且我需要提供一個按鈕並單擊按鈕我將在框架中執行一些預定義的操作。
這是我的代碼。如何在自定義框架中捕獲UIButton的UIEvents?

public class WebButton: NSObject { 
    public func enableWebButton(enable:Bool) 
    { 
     if(enable) 
     { 
      let appWindow = UIApplication.sharedApplication().keyWindow 
      let webBtn = UIButton(frame:CGRectMake((appWindow?.frame.size.width)! - 70,(appWindow?.frame.size.height)! - 70,50,50)) 
      let frameworkBundle = NSBundle(forClass: self.classForCoder) 
      let img = UIImage(named: "btn_icon.png", inBundle: frameworkBundle, compatibleWithTraitCollection: nil) 
      webBtn.setImage(img, forState: .Normal) 
      webBtn.layer.cornerRadius = webBtn.frame.size.width/2; 
      webBtn.layer.masksToBounds = true 
      webBtn.addTarget(self, action: "webButtonClick", forControlEvents: .TouchUpInside) 
      appWindow?.addSubview(webBtn) 
      print("btn created") 
     } 
    } 

    func webButtonClick() 
    { 
     print("btn Clicked") 
    } 
} 

在這段代碼中,我在我的示例項目上找到按鈕,但是單擊按鈕時沒有任何反應。

「BTN創建」

日誌是要打印,但

「BTN點擊了」

永遠不會打印。
請幫我解決這個問題。
在此先感謝。

回答

0

嘗試使用此代碼創建按鈕,您的webButtonClick功能:

public func enableWebButton(enable:Bool) 
{ 
    if(enable) 
    { 
     let appWindow = UIApplication.sharedApplication().keyWindow 
     let webBtn = UIButton(frame:CGRectMake((appWindow?.frame.size.width)! - 70,(appWindow?.frame.size.height)! - 70,50,50)) 
     let frameworkBundle = NSBundle(forClass: self.classForCoder) 
     let img = UIImage(named: "btn_icon.png", inBundle: frameworkBundle, compatibleWithTraitCollection: nil) 
     webBtn.setImage(img, forState: .Normal) 
     webBtn.layer.cornerRadius = webBtn.frame.size.width/2; 
     webBtn.layer.masksToBounds = true 
     webBtn.addTarget(self, action: "webButtonClick:", forControlEvents: UIControlEvents.TouchUpInside) 
     appWindow?.addSubview(webBtn) 
     print("btn created") 
    } 
} 


func webButtonClick(sender:UIButton!) 
{ 
    print("btn Clicked") 
} 
+0

已經嘗試過,但沒有成功,還增加了'@ IBAction'前'func'但被顯示在沒有成功 –

+0

按鈕屏幕? –

+0

是的,按鈕與我的圖像一起顯示 –