UIImageView - 如何获取分配的图像的文件名?

发布于 2024-08-11 03:21:38 字数 214 浏览 12 评论 0原文

是否可以读取 UIImageView 的 UIImage 的名称 目前存储在 UIImageView 中?

我希望你能做一些类似的事情,但还没有弄清楚。

NSString *currentImageName = [MyIImageView getFileName];

Is it possible to read the name of an UIImageView's UIImage
that's presently stored in the UIImageView?

I was hoping you could do something kind of like this, but haven't figured it out.

NSString *currentImageName = [MyIImageView getFileName];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

萧瑟寒风 2024-08-18 03:21:38

您可以对 UIView 的任何子类使用 setAccessibilityIdentifier 方法

UIImageView *image ;
[image setAccessibilityIdentifier:@"file name"] ;

NSString *file_name = [image accessibilityIdentifier] ;

you can use setAccessibilityIdentifier method for any subclass of UIView

UIImageView *image ;
[image setAccessibilityIdentifier:@"file name"] ;

NSString *file_name = [image accessibilityIdentifier] ;
述情 2024-08-18 03:21:38

没有。你不能那样做。

原因是 UIImageView 实例不存储图像文件。它存储一个显示 UIImage 实例。当您从文件创建图像时,您会执行以下操作:

UIImage *picture = [UIImage imageNamed:@"myFile.png"];

完成此操作后,将不再有任何对文件名的引用。 UIImage 实例包含数据,无论它从哪里获取。因此,UIImageView 不可能知道文件名。

另外,即使可以,您也永远不会从视图中获取文件名信息。这破坏了 MVC。

Nope. You can't do that.

The reason is that a UIImageView instance does not store an image file. It stores a displays a UIImage instance. When you make an image from a file, you do something like this:

UIImage *picture = [UIImage imageNamed:@"myFile.png"];

Once this is done, there is no longer any reference to the filename. The UIImage instance contains the data, regardless of where it got it. Thus, the UIImageView couldn't possibly know the filename.

Also, even if you could, you would never get filename info from a view. That breaks MVC.

小梨窩很甜 2024-08-18 03:21:38

不不不……一般来说这些事情都是可能的。这只会让你觉得自己是个肮脏的人。如果您绝对必须这样做,请执行以下操作:

我可以验证这是否有效,但需要注意的是您无法获取 NIB 中加载的 UIImage 的名称。看来从 NIB 加载的图像不是通过任何标准函数调用创建的,所以这对我来说确实是一个谜。

我将实施工作留给你。复制粘贴破坏 Objective-C 运行时的代码是一个非常糟糕的主意,因此请仔细考虑您的项目需求,只有在必要时才实现它。

No no no… in general these things are possible. It'll just make you feel like a dirty person. If you absolutely must, do this:

  • Create a category with your own implementation of +imageNamed:(NSString*)imageName that calls through to the existing implementation and uses the technique identified here (How do I use objc_setAssociatedObject/objc_getAssociatedObject inside an object?) to permanently associate imageName with the UIImage object that is returned.

  • Use Method Swizzling to swap the provided implementation of imageNamed: for your implementation in the method lookup table of the Objective-C runtime.

  • Access the name you associated with the UIImage instance (using objc_getAssociatedObject) anytime you want it.

I can verify that this works, with the caveat that you can't get the names of UIImage's loaded in NIBs. It appears that images loaded from NIBs are not created through any standard function calls, so it's really a mystery to me.

I'm leaving the implementation up to you. Copy-pasting code that screws with the Objective-C runtime is a very bad idea, so think carefully about your project's needs and implement this only if you must.

白色秋天 2024-08-18 03:21:38

没有本地方法可以做到这一点;但是,您可以自己轻松地创建此行为。

您可以子类化 UIImageView 并添加一个新的实例变量:

NSString* imageFileName;

然后您可以覆盖 setImage,首先将 imageFileName 设置为您要的图像的文件名设置,然后调用[super setImage:imageFileName]。像这样的事情:

-(void) setImage:(NSString*)fileName
{
   imageFileName = fileName;
   [super setImage:fileName];
}

仅仅因为它不能在本地完成并不意味着它不可能:)

There is no native way to do this; however, you could easily create this behavior yourself.

You can subclass UIImageView and add a new instance variable:

NSString* imageFileName;

Then you could override setImage, first setting imageFileName to the filename of the image you're setting, and then calling [super setImage:imageFileName]. Something like this:

-(void) setImage:(NSString*)fileName
{
   imageFileName = fileName;
   [super setImage:fileName];
}

Just because it can't be done natively doesn't mean it isn't possible :)

铜锣湾横着走 2024-08-18 03:21:38
if ([imageForCheckMark.image isEqual:[UIImage imageNamed:@"crossCheckMark.png"]]||[imageForCheckMark.image isEqual:[UIImage imageNamed:@"checkMark.png"]])
{

}
if ([imageForCheckMark.image isEqual:[UIImage imageNamed:@"crossCheckMark.png"]]||[imageForCheckMark.image isEqual:[UIImage imageNamed:@"checkMark.png"]])
{

}
少钕鈤記 2024-08-18 03:21:38

没有。本地没有办法做到这一点。
您必须继承 UIImageView 的子类,并添加 imageFileName 属性(在设置图像时设置)。

Nope. No way to do that natively.
You're going to have to subclass UIImageView, and add an imageFileName property (which you set when you set the image).

睫毛溺水了 2024-08-18 03:21:38

UIImageView 和 UIImage 都不保留加载图像的文件名。

您可以

1:(如上面 Kenny Winker 所建议的)将 UIImageView 子类化以具有 fileName 属性,或者

2:用数字命名图像文件(image1.jpg、image2.jpg 等)并用相应的数字标记这些图像(tag= 1 对于 image1.jpg,tag=2 对于 image2.jpg 等)或

3:有一个类级别变量(例如 NSString *currentFileName),每当您更新 UIImageView 的图像时该变量都会更新

Neither UIImageView not UIImage holds on to the filename of the image loaded.

You can either

1: (as suggested by Kenny Winker above) subclass UIImageView to have a fileName property or

2: name the image files with numbers (image1.jpg, image2.jpg etc) and tag those images with the corresponding number (tag=1 for image1.jpg, tag=2 for image2.jpg etc) or

3: Have a class level variable (eg. NSString *currentFileName) which updates whenever you update the UIImageView's image

不疑不惑不回忆 2024-08-18 03:21:38

简而言之:

uiImageView.image?.imageAsset?.value(forKey: "assetName")

UIImage 有一个 imageAsset 属性(自 iOS 8.0 起),该属性引用它所创建的 UIImageAsset(如果有)。

UIImageAsset 有一个 assetName 属性,其中包含您想要的信息。不幸的是它不是公开的,因此需要使用 value(forKey: "assetName")。请自行承担使用风险,因为它已正式超出 App Store 范围。

In short:

uiImageView.image?.imageAsset?.value(forKey: "assetName")

UIImage has an imageAsset property (since iOS 8.0) that references the UIImageAsset it was created from (if any).

UIImageAsset has an assetName property that has the information you want. Unfortunately it is not public, hence the need to use value(forKey: "assetName"). Use at your own risk, as it's officially out of bounds for the App Store.

锦上情书 2024-08-18 03:21:38

或者您可以使用恢复标识符,如下所示:

let myImageView = UIImageView()
myImageView.image = UIImage(named: "anyImage")
myImageView.restorationIdentifier = "anyImage" // Same name as image's name!

// Later, in UI Tests:
print(myImageView.restorationIdentifier!) // Prints "anyImage"

基本上,在此解决方案中,您使用恢复标识符来保存图像的名称,以便以后可以在任何地方使用它。如果更新图像,则还必须更新恢复标识符,如下所示:

myImageView.restorationIdentifier = "newImageName"

希望对您有帮助,祝您好运!

Or you can use the restoration identifier, like this:

let myImageView = UIImageView()
myImageView.image = UIImage(named: "anyImage")
myImageView.restorationIdentifier = "anyImage" // Same name as image's name!

// Later, in UI Tests:
print(myImageView.restorationIdentifier!) // Prints "anyImage"

Basically in this solution you're using the restoration identifier to hold the image's name, so you can use it later anywhere. If you update the image, you must also update the restoration identifier, like this:

myImageView.restorationIdentifier = "newImageName"

I hope that helps you, good luck!

嘴硬脾气大 2024-08-18 03:21:38

此代码将帮助您:-

- (NSString *)getFileName:(UIImageView *)imgView{
    NSString *imgName = [imgView image].accessibilityIdentifier;
    NSLog(@"%@",imgName);
    return imgName;
}

将此用作:-

NSString *currentImageName = [self getFileName:MyIImageView];

This code will help you out:-

- (NSString *)getFileName:(UIImageView *)imgView{
    NSString *imgName = [imgView image].accessibilityIdentifier;
    NSLog(@"%@",imgName);
    return imgName;
}

Use this as:-

NSString *currentImageName = [self getFileName:MyIImageView];
夜雨飘雪 2024-08-18 03:21:38

是的,您可以借助以下代码之类的数据进行比较

UITableViewCell *cell = (UITableViewCell*)[self.view viewWithTag:indexPath.row + 100];

UIImage *secondImage = [UIImage imageNamed:@"boxhover.png"];

NSData *imgData1 = UIImagePNGRepresentation(cell.imageView.image);
NSData *imgData2 = UIImagePNGRepresentation(secondImage);

BOOL isCompare =  [imgData1 isEqual:imgData2];
if(isCompare)
{
    //contain same image
    cell.imageView.image = [UIImage imageNamed:@"box.png"];
}
else
{
    //does not contain same image
    cell.imageView.image = secondImage;
}

Yes you can compare with the help of data like below code

UITableViewCell *cell = (UITableViewCell*)[self.view viewWithTag:indexPath.row + 100];

UIImage *secondImage = [UIImage imageNamed:@"boxhover.png"];

NSData *imgData1 = UIImagePNGRepresentation(cell.imageView.image);
NSData *imgData2 = UIImagePNGRepresentation(secondImage);

BOOL isCompare =  [imgData1 isEqual:imgData2];
if(isCompare)
{
    //contain same image
    cell.imageView.image = [UIImage imageNamed:@"box.png"];
}
else
{
    //does not contain same image
    cell.imageView.image = secondImage;
}
一场信仰旅途 2024-08-18 03:21:38

您可以使用 Objective C 运行时功能将 imagename 与 UImageView 关联起来。

首先在您的类中导入 #import

然后实现您的代码如下:

NSString *filename = @"exampleImage";
UIImage *image = [UIImage imagedName:filename];
objc_setAssociatedObject(image, "imageFilename", filename, OBJC_ASSOCIATION_COPY);
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
//You can then get the image later:
NSString *filename = objc_getAssociatedObject(imageView, "imageFilename");

希望对您有帮助。

You can use objective c Runtime feature for associating imagename with the UImageView.

First import #import <objc/runtime.h> in your class

then implement your code as below :

NSString *filename = @"exampleImage";
UIImage *image = [UIImage imagedName:filename];
objc_setAssociatedObject(image, "imageFilename", filename, OBJC_ASSOCIATION_COPY);
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
//You can then get the image later:
NSString *filename = objc_getAssociatedObject(imageView, "imageFilename");

Hope it helps you.

情痴 2024-08-18 03:21:38

获取图像名称 Swift 4.2

如果您想比较资源中的按钮图像名称,有一种方法。

@IBOutlet weak var extraShotCheckbox: UIButton!

@IBAction func extraShotCheckBoxAction(_ sender: Any) {
    extraShotCheckbox.setImage(changeCheckBoxImage(button: extraShotCheckbox), for: .normal)
}

func changeCheckBoxImage(button: UIButton) -> UIImage {
    if let imageView = button.imageView, let image = imageView.image {
        if image == UIImage(named: "checkboxGrayOn") {
            return UIImage(named: "checkbox")!
        } else {
            return UIImage(named: "checkboxGrayOn")!
        }
    }
    return UIImage()
}

Get image name Swift 4.2

There is a way if you want to compare button image names that you have in assets.

@IBOutlet weak var extraShotCheckbox: UIButton!

@IBAction func extraShotCheckBoxAction(_ sender: Any) {
    extraShotCheckbox.setImage(changeCheckBoxImage(button: extraShotCheckbox), for: .normal)
}

func changeCheckBoxImage(button: UIButton) -> UIImage {
    if let imageView = button.imageView, let image = imageView.image {
        if image == UIImage(named: "checkboxGrayOn") {
            return UIImage(named: "checkbox")!
        } else {
            return UIImage(named: "checkboxGrayOn")!
        }
    }
    return UIImage()
}
半衬遮猫 2024-08-18 03:21:38

Swift 3

首先将accessibilityIdentifier设置为imageName

myImageView.image?.accessibilityIdentifier = "add-image"

,然后使用以下代码。

extension UIImageView {
  func getFileName() -> String? {
    // First set accessibilityIdentifier of image before calling.
    let imgName = self.image?.accessibilityIdentifier
    return imgName
  }
}

最后,方法的调用方式来识别

myImageView.getFileName()

Swift 3

First set the accessibilityIdentifier as imageName

myImageView.image?.accessibilityIdentifier = "add-image"

Then Use the following code.

extension UIImageView {
  func getFileName() -> String? {
    // First set accessibilityIdentifier of image before calling.
    let imgName = self.image?.accessibilityIdentifier
    return imgName
  }
}

Finally, The calling way of method to identify

myImageView.getFileName()
独﹏钓一江月 2024-08-18 03:21:38

我已经处理过这个问题,我已经通过MVC设计模式解决了它,我创建了Card类:

@interface Card : NSObject

@property (strong,nonatomic) UIImage* img;

@property  (strong,nonatomic) NSString* url;

@end

//然后在UIViewController中的DidLoad方法中执行:

// init Cards
Card* card10= [[Card alloc]init];
card10.url=@"image.jpg";  
card10.img = [UIImage imageNamed:[card10 url]];

< strong>//例如

UIImageView * myImageView = [[UIImageView alloc]initWithImage:card10.img];
[self.view addSubview:myImageView];

//您可能想检查图像名称,所以您可以这样做:

//例如

 NSString * str = @"image.jpg";

 if([str isEqualToString: [card10 url]]){
 // your code here
 }

I have deal with this problem, I have been solved it by MVC design pattern, I created Card class:

@interface Card : NSObject

@property (strong,nonatomic) UIImage* img;

@property  (strong,nonatomic) NSString* url;

@end

//then in the UIViewController in the DidLoad Method to Do :

// init Cards
Card* card10= [[Card alloc]init];
card10.url=@"image.jpg";  
card10.img = [UIImage imageNamed:[card10 url]];

// for Example

UIImageView * myImageView = [[UIImageView alloc]initWithImage:card10.img];
[self.view addSubview:myImageView];

//may you want to check the image name , so you can do this:

//for example

 NSString * str = @"image.jpg";

 if([str isEqualToString: [card10 url]]){
 // your code here
 }
儭儭莪哋寶赑 2024-08-18 03:21:38

使用下面

 UIImageView *imageView = ((UIImageView *)(barButtonItem.customView.subviews.lastObject));
 file_name = imageView.accessibilityLabel;

use below

 UIImageView *imageView = ((UIImageView *)(barButtonItem.customView.subviews.lastObject));
 file_name = imageView.accessibilityLabel;
烂人 2024-08-18 03:21:38

该代码在 swift3 中工作 - 在 didFinishPickingMediaWithInfo 委托方法中编写代码:

if let referenceUrl = info[UIImagePickerControllerReferenceURL] as? NSURL {
  ALAssetsLibrary().asset(for: referenceUrl as URL!, resultBlock: { asset in

  let fileName = asset?.defaultRepresentation().filename()
  print(fileName!)

  //do whatever with your file name            
  }, failureBlock: nil)
}

The code is work in swift3 - write code inside didFinishPickingMediaWithInfo delegate method:

if let referenceUrl = info[UIImagePickerControllerReferenceURL] as? NSURL {
  ALAssetsLibrary().asset(for: referenceUrl as URL!, resultBlock: { asset in

  let fileName = asset?.defaultRepresentation().filename()
  print(fileName!)

  //do whatever with your file name            
  }, failureBlock: nil)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文