UIButton图像与状态

时间:2013-08-22 23:08:35

标签: iphone ios objective-c uibutton uiimage

我有UIButton并使用正确的代码设置其背景图片。

`[button setImage:self.image forState:UIControlStateNormal]`

并在按钮初始化时显示正确的图像,但我想在状态为UIControlStateSelected时使图像消失。

我可以在选择图像时更改图像,但在选择时不知道哪个是正确的功能或值设置为无图像。

我应该将image alpha设为0.0吗?

谢谢!

4 个答案:

答案 0 :(得分:4)

使用photoshop,创建具有透明背景的新图像。将其另存为nope.png文件,将其拖到项目中。然后

[button setImage:[UIImage imageNamed:@"nope.png"] forState:UIControlStateSelected];

另一种方式是您需要创建新的图片类别:

@interface UIImage (UIImageFrameColor)
+(UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size;
@end

@implementation UIImage (UIImageFrameColor)
+(UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size
{
    UIGraphicsBeginImageContextWithOptions(size, YES, 0);

    [color set];
    UIBezierPath * path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, size.width, size.height)];
    [path fill];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext ();
    UIGraphicsEndImageContext();

    return image;
}
@end

然后你需要让图像具有相同颜色的按钮晚餐视图的背景颜色

    UIImage *bgImage = [UIImage imageWithColor:button.supperview.backgroundColor andSize:button.frame.size];
    [button setImage:bgImage forState:UIControlStateSelected];

答案 1 :(得分:1)

尝试[button setImage:nil forState:UIControlStateSelected];

希望这有帮助!

答案 2 :(得分:1)

尝试[button setSeleted:YES];

如果要创建像检查列表按钮这样的按钮。这是一个示例代码:

[button setImage:imageNormal forState:UIControlStateNormal];
[button setImage:imageSelected forState:UIControlStateSelected];
.....

-(void)btnButtonPressed:(UIButton*)sender {
    [sender setSelected:!sender.selected];
}

希望这对你有帮助!

答案 3 :(得分:1)

请检查并尝试。这可能对您有用:

[button setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateHighlighted];
[button setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];