如何创建具有相同Buttonsystemitem单击效果的自定义UIButton

时间:2015-08-18 12:03:15

标签: ios swift uinavigationcontroller

我正在为导航栏创建一个自定义按钮项,我希望它与按钮系统项具有相同的效果(慢速淡出) 这是我的代码:

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

3 个答案:

答案 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)