簡體   English   中英

Objective-C-如何將多個圖像添加到標簽上顯示的數組?

[英]objective-c - How to add multiple images to an array shown on a label?

我試圖在標簽上顯示有時的照片和有時的事實。 為此,我在.m文件中有一個包含事實的數組,其中包括用於隨機生成的內容的arcm4。

- (instancetype) init {
    self = [super init];
    if (self) {
        _Facts = @[
                   @"The length of an elephant is the same as the tongue of a blue whale.",
                   @"The crocodile’s tongue is unmovable, as it is attached to the roof of its mouth."
                   ];
    }
    return self;
}

- (void)populateLabel:(UILabel *)Label {
    int random = arc4random_uniform(@(_aFacts.count).intValue);
    NSObject * element = _aFacts[random];
    if ([element isKindOfClass:NSString.class]) {
        //        NSLog(@"Will add string");
        Label.attributedText = nil;
        Label.text = (NSString*) element;
    } else if ([element isKindOfClass:NSAttributedString.class]) {
        //        NSLog(@"Will add image");
        Label.text = nil;
        Label.attributedText = (NSAttributedString*)element;
    } else {
        NSLog(@"_aFacts array is supposed to contain only NSString(s) and NSAttributedString(s). Instead a %@ has been found at index %d", NSStringFromClass(element.class), random);
    }
}

然后,我想通過添加以下代碼來包含圖像:

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"196H"];
NSAttributedString *attributedString = [NSAttributedString attributedStringWithAttachment:attachment];

在最后一項之后的和數組中:

, attributedString

我在我的viewController文件中調用此代碼:

[self.aFactBook populateLabel:self.Label];

所以這段代碼很好用,但是

  1. 我需要包含200多張圖片
  2. 有沒有比這樣更好的解決方案了?

謝謝你的幫助!

這取決於性能對您意味着什么。 有時確實值得緩存200張圖像,因此您可以很好地操作它們,有時200張圖像可以擴展到10,000張圖像,然后您想要存儲它們的名稱並僅在需要時加載它們,而不是將所有圖像都保留在內存中。

也許您應該考慮使用類似SQLite或CoreData之類的數據庫。

保留數據的最佳方法是使用數據庫。 我個人推薦SQLite,它是非常簡單且功能強大的DMS。 另外,如果將來需要進一步擴展數據庫,則無需更改代碼,只需更改數據庫的記錄即可。

您可以對圖像使用BLOB(數據類型),對事實使用VARCHAR(這些數據類型用於數據庫表的構建)。

如果您對我的回答感到滿意,請不要忘記豎起大拇指!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM