ios - 应用程序激活后图像比较不起作用

标签 ios iphone image ios6

我正在使用以下内容来比较按钮的背景图像。

if([[button currentBackgroundImage] isEqual:[UIImage imageNamed:@"image1.png"]]){
      // do something
}

当应用程序处于事件状态时,代码可以正常工作。但是当应用程序从空闲状态返回时,上述代码将不起作用。

知道为什么会发生这种情况吗?

谢谢

最佳答案

从后台返回后,图像不会进行比较,因为您正在使用 [UIImage imageNamed:@"image1.png"] 创建该图像的新实例以进行比较(图像通过查看其哈希值进行比较,而不是通过查看实际图像内容)。如果您为图像创建一个属性,那么当您第一次使用 imageNamed: 并在比较中使用它时,它应该可以正常工作。所以,我用这段代码进行了测试,当我从后台返回后检查时,它返回true(我在IB中设置了按钮的背景图像)。

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *greenButton;
@property (strong,nonatomic) UIImage *greenPng;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.greenPng = [UIImage imageNamed:@"Green.png"];
}

- (IBAction)checkImages:(id)sender {

    BOOL isTheSame = [self.greenButton.currentBackgroundImage isEqual:self.greenPng];
    NSLog(@"The images are %@",isTheSame? @"the same" : @"different");
    NSLog(@" button image hash is %d",self.greenButton.currentBackgroundImage.hash);
    NSLog(@" imageNamed image hash is %d",self.greenPng.hash);
}

编辑后:我不确定我的解释是否完全正确 - 在应用程序的一次运行中,您可以多次调用 imageNamed:,并且返回的所有图像都将具有相同的哈希值(包括您在 IB 中选择的图像,如果您这样做的话)。我认为这是由于现金。无论如何,当您从后台返回并再次调用 imageNamed: 时,它会返回具有不同哈希值的图像。

关于ios - 应用程序激活后图像比较不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20440956/

相关文章:

ios - 识别 Apple Watch 名称

ios - 接收推送通知时显示 View Controller 不起作用,其 View 不在窗口层次结构中

javascript - jquery - 拉伸(stretch)背景图像以填充文档而不是窗口?

iphone - 是否可以自定义@synthesized 属性?

javascript - Github图像差异滑动模式-如何实现?

php - 如何通过ajax从服务器发送png图片到浏览器显示

ios - 如何使用 AVCaptureSession 从 CMSampleBuffer 获取 UIImage

ios - Xcode 从 10.2 降级到 10.1 后不显示模拟器

iphone - 如何将选项卡栏 Controller 放在 View Controller 而不是委托(delegate)中?

iphone - 多个注释未显示在 Iphone map View 中