code

UIImageView-할당 된 이미지의 파일 이름을 얻는 방법은 무엇입니까?

codestyles 2020. 10. 13. 07:51
반응형

UIImageView-할당 된 이미지의 파일 이름을 얻는 방법은 무엇입니까?


UIImageView's UIImage현재 저장된의 이름을 읽을 수 UIImageView있습니까?

당신이 이런 일을 할 수 있기를 바랐지만 아직 알아 내지 못했습니다.

NSString *currentImageName = [MyIImageView getFileName];

아니. 당신은 그렇게 할 수 없습니다.

그 이유는 UIImageView인스턴스가 이미지 파일을 저장하지 않기 때문입니다 . 디스플레이 UIImage인스턴스를 저장 합니다. 파일에서 이미지를 만들 때 다음과 같이합니다.

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

이 작업이 완료되면 더 이상 파일 이름에 대한 참조가 없습니다. UIImage인스턴스는 관계없이 그것을 가지고 어디에 데이터가 포함되어 있습니다. 따라서 UIImageView파일 이름을 알 수 없습니다.

또한 가능하더라도 뷰에서 파일 이름 정보를 얻을 수 없습니다. 그것은 MVC를 깨뜨립니다.


UIView의 모든 하위 클래스에 setAccessibilityIdentifier 메서드를 사용할 수 있습니다.

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

NSString *file_name = [image accessibilityIdentifier] ;

아니오 아니오 아니오… 일반적으로 이러한 일이 가능합니다. 그것은 당신을 더러운 사람처럼 느끼게 할 것입니다. 꼭 필요한 경우 다음을 수행하십시오.

  • +imageNamed:(NSString*)imageName기존 구현에 대한 호출 의 자체 구현으로 범주를 만들고 여기에 식별 된 기술 ( 개체 내에서 objc_setAssociatedObject / objc_getAssociatedObject를 사용하는 방법 )을 imageName사용하여 반환 된 UIImage 개체와 영구적으로 연결 합니다.

  • Objective-C 런타임의 메서드 조회 테이블에서 구현에 대해 제공된 구현을 바꾸려면 메서드 전환을 사용 imageNamed:합니다.

  • 원할 때마다 UIImage 인스턴스 (objc_getAssociatedObject 사용)와 연결 한 이름에 액세스합니다.

NIB에로드 된 UIImage의 이름을 가져올 수 없다는 경고와 함께 이것이 작동하는지 확인할 수 있습니다. NIB에서로드 된 이미지는 표준 함수 호출을 통해 생성되지 않는 것 같아서 정말 미스테리입니다.

구현은 귀하에게 맡기겠습니다. Objective-C 런타임과 관련된 코드를 복사하여 붙여 넣는 것은 매우 나쁜 생각이므로 프로젝트의 요구 사항을 신중하게 생각하고 필요한 경우에만 구현하십시오.


이를 수행하는 고유 한 방법은 없습니다. 그러나이 동작을 직접 쉽게 만들 수 있습니다.

하위 클래스 UIImageView를 만들고 새 인스턴스 변수를 추가 할 수 있습니다 .

NSString* imageFileName;

그런 다음을 재정의 setImage하고 먼저 설정 imageFileName중인 이미지의 파일 이름을 설정 한 다음 [super setImage:imageFileName]. 이 같은:

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

기본적으로 할 수 없다고해서 불가능하다는 의미는 아닙니다. :)


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

}

아니. 기본적으로 할 방법이 없습니다. UIImageView를 하위 클래스로 만들고 imageFileName 속성 (이미지를 설정할 때 설정)을 추가해야합니다.


UIImage가 아닌 UIImageView는로드 된 이미지의 파일 이름을 보유하지 않습니다.

당신은

1 : (위의 Kenny Winker가 제안한대로) 하위 클래스 UIImageView가 fileName 속성을 갖거나

2 : 이미지 파일의 이름을 숫자 (image1.jpg, image2.jpg 등)로 지정하고 해당 번호 (image1.jpg의 경우 tag = 1, image2.jpg의 경우 tag = 2 등)로 해당 이미지에 태그를 지정하거나

3 : UIImageView의 이미지를 업데이트 할 때마다 업데이트되는 클래스 수준 변수 (예 : NSString * currentFileName)가 있습니다.


이 코드는 당신을 도울 것입니다 :-

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

이것을 다음과 같이 사용하십시오.

NSString *currentImageName = [self getFileName:MyIImageView];

예, 아래 코드와 같은 데이터의 도움으로 비교할 수 있습니다.

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;
}

UImageView와 이미지 이름을 연결하기 위해 객관적인 c 런타임 기능을 사용할 수 있습니다.

#import <objc/runtime.h>수업에서 먼저 가져 오기

그런 다음 아래와 같이 코드를 구현하십시오.

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");

도움이 되었기를 바랍니다.


또는 다음과 같이 복원 식별자를 사용할 수 있습니다.

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"

도움이 되었기를 바랍니다. 행운을 빕니다!


스위프트 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 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()
}

나는이 문제를 다루었 고 MVC 디자인 패턴으로 해결했으며 Card 클래스를 만들었습니다.

@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
 }

use below

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

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)
}

참고URL : https://stackoverflow.com/questions/1740274/uiimageview-how-to-get-the-file-name-of-the-image-assigned

반응형