Preamble
To add text to a label you write this (as you are doing now).
self.label.text = @"This is a test";
To add an image you write this.
NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"refresh"];
self.label.attributedText = [NSAttributedString attributedStringWithAttachment:attachment];
So we should do the following changes to your code.
1. Populating the array.
You should not add the image directly inside the array. Add an NSAttributedString
instead. So your init becomes:
- (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. Updating randomAFact
Delete your randomFact method and add this new version.
- (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);
}
}
As you can see this method receives as parameter a UILabel
and populates it with a random value from _aFacts
.
3. Calling populateLabel
Now you will need to update the code that populates your label.
So where you have something like this:
self.label.text = [self.aFactBook randomAFact];
you will need to use this:
[self.aFactBook populateLabel:self.label];
Hope it helps.