2016-08-02 43 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

是的,按钮与我的图像一起显示 –