programing

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

sourcejob 2023. 9. 6. 22:02
반응형

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

이름을 읽을 수 있나요?UIImageView's UIImage그것은다에 .UIImageView?

당신이 이런 일을 할 수 있기를 바랬는데, 아직 알아내지 못했습니다.

NSString *currentImageName = [MyIImageView getFileName];

setAccessibility를 사용할 수 있습니다.UIView의 모든 하위 클래스에 대한 식별자 메서드

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

NSString *file_name = [image accessibilityIdentifier] ;

아뇨, 그럴 순 없어요

는 는a 입니다.UIImageViewfile을 .지을지다는다지을지 .합니다.UIImage과 같은합니다.파일로 이미지를 만들 때 다음과 같은 작업을 수행합니다.

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

이 작업이 완료되면 파일 이름에 대한 참조가 더 이상 없습니다.UIImage 데이터를 에 관계없이 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .는.UIImageView파일 이름을 알 수 없습니다.

또한, 가능하더라도 보기에서 파일 이름 정보를 얻을 수 없습니다.그건 MVC를 깨트립니다.

아니아니아니... 일반적으로 이런 일들이 가능합니다.당신을 더러운 사람처럼 느끼게 해줄 겁니다.꼭 해야 할 경우 다음 작업을 수행합니다.

  • 가 과 를 합니다 한 합니다 를 가 한 과 +imageNamed:(NSString*)imageName기존 구현을 호출하고 여기서 식별된 기술(객체 내부에서 objc_setAssociatedObject/objc_getAssociatedObject를 어떻게 사용합니까?)을 사용하여 영구적으로 연결합니다.imageNameUIImage 객체가 반환됩니다.

  • Method Swizzling을 사용하여 제공된 구현을 스왑합니다.imageNamed:Objective-C 런타임의 메서드 룩업 테이블에서 구현할 수 있습니다.

  • UIImage 인스턴스와 연결된 이름(objc_getAssociatedObject 사용)에 언제든지 액세스할 수 있습니다.

NIB에서 UIImage의 이름을 로드할 수 없다는 주의사항과 함께 이것이 작동하는지 확인할 수 있습니다.NIB에서 로드된 이미지는 표준 함수 호출을 통해 생성되지 않는 것으로 보여져서 저에게는 정말 수수께끼입니다.

실행은 당신에게 맡기겠습니다.Objective-C 런타임에 나사를 고정하는 코드를 복사 붙여넣기하는 것은 매우 좋지 않은 생각이므로 프로젝트의 요구 사항을 신중하게 고려하고 필요한 경우에만 이를 실행합니다.

기본적인 방법은 없지만 직접 이 동작을 만들 수 있습니다.

UIImageView변수를 합니다:스를다새다를스d새aed .

NSString* imageFileName;

그러면 당신은 당신을 무시할 수 있습니다.setImage 설정, imageFileName 이름으로 정인의일로음한음한o로정e일인fgn,deu'[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"]])
{

}

아니요, 그럴 리가 없어요UIMageView를 서브클래스하고 imageFileName 속성(이미지 설정 시 설정)을 추가해야 합니다.

UIImageView not UIImage 모두 로드된 이미지의 파일 이름을 유지하지 않습니다.

둘 중 하나라도

1: (위의 Kenny Winker가 제안한 대로) subclass UImageView fileName 속성 또는

2: 이미지 파일에 숫자(image1.jpg, image2.jpg 등)를 지정하고 해당 숫자(image1.jpg의 경우 tag=1, image2.jpg의 경우 tag=2) 또는 태그를 지정합니다.

3: 클래스 레벨 변수(예: 클래스 레벨 변수)를 갖습니다.UIMageView의 이미지를 업데이트할 때마다 업데이트되는 NSString *currentFileName)

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

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"

도움이 되길 바래요, 행운을 빌어요!

이 코드가 도움이 될 겁니다:-

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

이를 다음과 같이 사용합니다.

NSString *currentImageName = [self getFileName:MyIImageView];

간단히 말해서:

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

UIImage가 있습니다.imageAsset를는성 ( 8.0후 )를 하는 속성 8 이후UIImageAsset(있는 경우) 로부터 생성되었습니다.

UIImageAsset가 있습니다.assetName당신이 원하는 정보를 가지고 있는 부동산.유감스럽게도 공개되지 않았으므로 사용할 필요가 있습니다.value(forKey: "assetName")위험을 하세요. 공식적으로 앱스토어의 범위를 벗어났기 때문에 자신의 위험을 무릅쓰고 사용하세요.

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

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

목적 c 런타임 기능을 사용하여 이미지 이름을 UImageView와 연결할 수 있습니다.

번째 가져오기 #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");

도움이 되길 바랍니다.

이미지 이름 가져오기 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()
}

스위프트 3

먼저 접근성을 설정합니다.식별자(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()

저는 이 문제를 해결했고, MVC 디자인 패턴으로 해결했으며, Card class를 만들었습니다.

@interface Card : NSObject

@property (strong,nonatomic) UIImage* img;

@property  (strong,nonatomic) NSString* url;

@end

다음에 //그 UIViewControllerDidLoadDo :법:

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

// 예를 들어

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

//이미지 이름을 확인하여 다음 작업을 수행할 수 있습니다.

//예를 들어

 NSString * str = @"image.jpg";

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

아래에 쓰임

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

코드는 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)
}

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

반응형