objective-c - 如何在数组中显示UImage?

时间:2015-08-02 13:16:31

标签: ios objective-c arrays image

我试图在我的应用程序中显示图像而不是文本,所以我试图在我的文本数组中集成UIImages。我每次尝试实施错误都很糟糕,所以我决定问Objective-c pros。需要每一个帮助,欢迎!

这是我的.h数组代码:

// array
@property (nonatomic, strong) NSArray *aFacts;

// pich a random fact
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *randomAFact;

和我的.m数组代码

-(instancetype) init {
    self = [super init];
    if (self) {
        _aFacts = @[@"Humans are the only primates that don’t have pigment in the palms of their hands.",
                         [UIImage imageNamed:@"refresh"],
];

    }
    return self;
    }

// arcm4
-(NSString *)randomAFact {
    int random = arc4random_uniform((int)self.aFacts.count);
    return (self.aFacts)[random];
}

@end

此代码显示在标签中。您认为标签会在阵列中显示成功的集成图像吗?

1 个答案:

答案 0 :(得分:1)

序言

要将标签添加到标签上(正如您现在所做的那样)。

self.label.text = @"This is a test";

要添加图像,请编写此图像。

NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"refresh"];
self.label.attributedText = [NSAttributedString attributedStringWithAttachment:attachment];

因此我们应该对您的代码进行以下更改。

1。填充数组。

您不应该直接在数组中添加图像。改为添加NSAttributedString。所以你的init变成了:

- (instancetype) init {
    self = [super init];
    if (self) {
        NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
        attachment.image = [UIImage imageNamed:@"refresh"];
        NSAttributedString * attributedString = [NSAttributedString attributedStringWithAttachment:attachment];
        _aFacts = @[@"Humans are the only primates that don’t have pigment in the palms of their hands.", attributedString];
    }
    return self;
}

2。更新randomAFact

删除randomFact方法并添加此新版本。

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

正如您所看到的,此方法接收UILabel作为参数,并使用_aFacts中的随机值填充它。

3。调用populateLabel

现在您需要更新填充标签的代码。

所以你有这样的地方:

self.label.text = [self.aFactBook randomAFact];

你需要使用它:

[self.aFactBook populateLabel:self.label];

希望它有所帮助。