Reputation: 33
I'm trying to show in my app also images instead of text and so I'm trying to integrate UIImages in my text array. Badly I get every time I try to implement an error so I decided to ask objective-c pros. Every help is needed and welcome!
This is my .h array code:
// array
@property (nonatomic, strong) NSArray *aFacts;
// pich a random fact
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *randomAFact;
and my .m array code
-(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
This code is shown in a label. Do you think the label will show an successful integrated image in the array?
Upvotes: 0
Views: 110
Reputation: 59496
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.
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;
}
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
.
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.
Upvotes: 1