首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UIImageView 定時切換圖片並獲取當前圖片名稱:accessibilityIdentifier 技巧

     編輯:程式設計綜合問答

需求

UIImageView 以 Timer 每 0.5 秒隨機切換 5 張圖片,需隨時取得當前顯示圖片的檔名。

解決:使用 accessibilityIdentifier

@property (nonatomic, strong) IBOutlet UIImageView *imgView;
@property (nonatomic, strong) NSArray *imgArray; // 檔名陣列

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imgArray = @[@"tops.png", @"position_conv.png", @"stocks.png", @"home.png", @"report.png"];
    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
}

- (void)changeImage {
    NSUInteger idx = arc4random_uniform((uint32_t)self.imgArray.count);
    NSString *name = self.imgArray[idx];
    self.imgView.image = [UIImage imageNamed:name];
    // 關鍵:將檔名存入 accessibilityIdentifier
    self.imgView.image.accessibilityIdentifier = name;
}

- (IBAction)getCurrentImageName:(id)sender {
    NSString *currentName = self.imgView.image.accessibilityIdentifier;
    NSLog(@"Current image: %@", currentName ?? @"nil");
}

優點

  • 不需額外成員變數追蹤索引。
  • 圖片物件本身攜帶標識,隨時可取。
  • 符合無障礙設計規範,一舉兩得。

替代方案

  • 成員變數 currentImageIndex 記錄索引。
  • 子類別 UIImage 增加 fileName 屬性(需關聯物件)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved