jef*_*leo 2 image button uibarbuttonitem ios swift
在viewDidload方法中,我已经声明了一个按钮并设置了RightBarButton ...
let btnFavourite = UIButton(frame: CGRectMake(0,0,30,30))
btnFavourite.addTarget(self, action: "btnFavourite:", forControlEvents: .TouchUpInside)
btnFavourite.setImage(UIImage(named: "star"), forState: .Normal)
btnFavourite.setImage(UIImage(named: "star_filled"), forState: .Highlighted)
let rightButton = UIBarButtonItem(customView: btnFavourite)
self.navigationItem.setRightBarButtonItems([rightButton], animated: true)
Run Code Online (Sandbox Code Playgroud)
如何从图像'star.png'按下按钮然后更改为'star_filled.png'?然后按'star_filled.png'中的按钮到'star.png'?
如何使两个功能像
func btnFavourite()
{
//clicked the favourite button then image change to star_filled.png
}
fun btnUnfavourite()
{
//clicked the button then the bar button image change to star.png
}
Run Code Online (Sandbox Code Playgroud)
创建方法将根据状态更新您的按钮 self.isFavourited
var isFavourited = false;//declare this above the viewDidload()
func updateRighBarButton(isFavourite : Bool){
let btnFavourite = UIButton(frame: CGRectMake(0,0,30,30))
btnFavourite.addTarget(self, action: "btnFavouriteDidTap", forControlEvents: .TouchUpInside)
if isFavourite {
btnFavourite.setImage(UIImage(named: "star_filled"), forState: .Normal)
}else{
btnFavourite.setImage(UIImage(named: "star"), forState: .Normal)
}
let rightButton = UIBarButtonItem(customView: btnFavourite)
self.navigationItem.setRightBarButtonItems([rightButton], animated: true)
}
func btnFavouriteDidTap()
{
//do your stuff
self.isFavourited = !self.isFavourited;
if self.isFavourited {
self.favourite();
}else{
self.unfavourite();
}
self.updateRighBarButton(self.isFavourited);
}
func favourite()
{
//do your favourite stuff/logic
}
func unfavourite(){
//do your unfavourite logic
}
Run Code Online (Sandbox Code Playgroud)
在viewDidload方法中,第一次调用,即
self.updateRighBarButton(self.isFavourited);//first time self.isFavourited will be false
Run Code Online (Sandbox Code Playgroud)