UIButton选择器未在导航栏内调用

时间:2016-06-07 12:52:30

标签: ios swift

我尝试将UIButton添加到导航栏的中心。

我的导航控制器已使用标签栏控制器进行初始化。 然后我创建一个带有自定义图像的UIButton

我的问题是,即使我可以看到按钮被按下,也不会调用选择器,因为播放了图像动画(按下按钮时)。

这是我的代码:

let navigationController = UINavigationController(rootViewController: tabBarController)

let image = UIImage(named: "logo")

let but = UIButton(type: .Custom)
navigationController.navigationBar.addSubview(but)
but .setImage(image, forState: .Normal)
but.frame=CGRectMake((self.view.frame.size.width-image!.size.width)/2.0, (navigationController.navigationBar.frame.size.height-image!.size.height)/2.0, image!.size.width, image!.size.height)

but.addTarget(self, action: #selector(self.initTabView), forControlEvents: .AllEvents)
but.addTarget(self, action: #selector(self.initTabView), forControlEvents: .TouchDown)

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window!.rootViewController = navigationController

任何提示都将受到赞赏。

2 个答案:

答案 0 :(得分:0)

查看forControlEvents

let but =  UIButton(type: .Custom)
but.frame = CGRectMake(0, 0, 100, 40) 
but.backgroundColor = UIColor.redColor()
but.setTitle("Button", forState: UIControlState.Normal)
but.addTarget(self, action: #selector(MyTabBarController.initTabView), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.titleView = but

要防止多次触摸按钮:

// default is false
but.exclusiveTouch = true 

答案 1 :(得分:0)

//试试这个 // Classname是,在其中存在类initTabView方法,您需要提供该类名

 but.addTarget(self, action: #selector(Classname.initTabView), forControlEvents: .TouchUpInside)