我正在为导航栏创建一个自定义按钮项,我希望它与按钮系统项具有相同的效果(慢速淡出) 这是我的代码:
var button_user : UIImage = UIImage(named:"user.png")!
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
button.setImage(UIImage(named: "user.png"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "user_clicked.png"), forState: UIControlState.Highlighted)
button.addTarget(self, action: nil, forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(0, 0, 28, 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
答案 0 :(得分:2)
您应该将UIButtonType.Custom
更改为UIButtonType.System
:
let button = UIButton(type: UIButtonType.System)
button.setImage(UIImage(named: "user.png"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "user_clicked.png"), forState: UIControlState.Highlighted)
button.addTarget(self, action: nil, forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(0, 0, 28, 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
修改强>
针对Swift 2.0进行了更新
答案 1 :(得分:1)
修改:您应该在导航栏中使用UIBarButtonItem
代替UIButton
。那样做。
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "backbutton"), style: UIBarButtonItemStyle.Plain, target: self, action: "buttonClicked:")
并添加方法
func buttonClicked(sender: AnyObject){
//Enter your code here
}
相应地为UIControlState
添加更多“图片”
答案 2 :(得分:1)
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
func buttonClicked(sender:UIButton)
{
dispatch_async(dispatch_get_main_queue(), {
if isHighLighted == false{
sender.highlighted = true;
isHighLighted = true
}else{
sender.highlighted = false;
isHighLighted = false
}
});
}
OR
button.setShowsTouchWhenHighlighted(true)