我们都见过QQ的点赞功能,点击之后空心的图片会变成实心,实际上这个过程是两个图片的切换过程,常态和点击之后的状态图片,废话不多说,代码奉上
-(UIButton *)zan_btn
{
UIButton * zan = [UIButtonbuttonWithType:UIButtonTypeCustom];
zan.frame =CGRectMake(36.25+55, 250 + 30, 35, 30);
//未点击时的默认图片(状态)
UIImage * image1 = [UIImageimageNamed:@"空心.png"];
[zan setImage:image1forState:UIControlStateNormal];
//点击之后的图片
UIImage * image2 = [UIImageimageNamed:@"实心.png"];
[zan setImage:image2forState:UIControlStateSelected];
[zan addTarget:selfaction:@selector(zan_clicked:)forControlEvents:UIControlEventTouchUpInside];
return zan;
}
-(void)zan_clicked:(id)sender
{
UIButton * button = (UIButton *)sender;
button.selected = ! button.selected;
}
然后将这个-(UIButton *)zan_btn;方法放在要用的位置上。第一次为点赞,第二次就取消。