我为iOS8应用编写了以下代码:
UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
[btnBack setFrame:CGRectMake(40, 30, 30, 30)];
[btnBack setBackgroundImage:[UIImage imageNamed:@"btn_close.png"]forState:UIControlStateNormal];
[btnBack setBackgroundImage:[UIImage imageNamed:@"btn_close_on.png"] forState:UIControlStateHighlighted|UIControlStateSelected];
[btnBack addTarget:self action:@selector(btnBackClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnBack];
点击时的方法:
-(void) btnBackClick:(id)sender{
[self.navigationController popToRootViewControllerAnimated:YES];
}
但是,单击按钮时图像的背景不会改变。唯一的影响是灰色。
如果我在xib文件上绘制该按钮,则图像更改就像魅力一样。
有什么不对吗?请帮忙。
答案 0 :(得分:0)
-(void) btnBackClick:(id)sender{
UIButton *myButton = (UIButton *)sender;
[myButton setSelected: YES]; // Add this line
[self.navigationController popToRootViewControllerAnimated:YES];
}
同样在viewWillAppear方法中设置与NO
相同[myButton setSelected: NO]; // Add this line
答案 1 :(得分:0)
UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
[btnBack setFrame:CGRectMake(40, 30, 30, 30)];
[btnBack setBackgroundImage:[UIImage imageNamed:@"btn_close.png"]forState:UIControlStateNormal];
[btnBack setBackgroundImage:[UIImage imageNamed:@"btn_close_on.png"] forState:UIControlStateHighlighted|UIControlStateSelected];
[btnBack addTarget:self action:@selector(btnBackClick:) forControlEvents:UIControlEventTouchUpInside];
[btnBack setSelected:YES];
[self.view addSubview:btnBack];
// ********** *******更新
UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
[btnBack setFrame:CGRectMake(40, 30, 30, 30)];
[btnBack setBackgroundImage:[UIImage imageNamed:@"btn_close.png"]forState:UIControlStateNormal];
[btnBack setBackgroundImage:[UIImage imageNamed:@"btn_close_on.png"] forState:UIControlStateHighlighted];
[btnBack setBackgroundImage:[UIImage imageNamed:@"btn_close_on.png"] forState:UIControlStateSelected];
[btnBack addTarget:self action:@selector(btnBackClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnBack];
-(void)btnBackClick:(UIButton *)btn
{
if ([btn isSelected])
{
[btn setSelected:NO];
}
else
[btn setSelected:YES];
}