简体   繁体   中英

NSTextAttachment image not displayed on iOS 8 devices (with iOS7.1 sdk)

I have just built my project on several iOS 8 devices with baseSDK set to iOS 7.1. Unfortunately, all NSTextAttachment images added as attributes to relevant instances of NSMutableAttributedString are hidden on iOS 8 devices and the iOS 8 simulator (they are still visible on devices with 7.1 and the iOS 7.1 simulator). The frame for these strings within their superviews is set as if the image was there, but the image itself is just not visible or rendered.

Has anybody else ran into the issue of text attachments not appearing on iOS 8. If so, is there a workaround? If not, is there something wrong with my code (pasted below)? This instance in particular sets an attributed title for a UIButton, but I have other instances with attachments that are simple UILabels that are displaying the same behavior.

NSMutableAttributedString *attrButtonTitle = [[NSMutableAttributedString alloc] initWithString:@"Let's go!"];
NSTextAttachment *doubleArrowIcon = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
doubleArrowIcon.image = [UIImage imageNamed:@"double-arrows"];
[attrButtonTitle appendAttributedString:[[NSAttributedString alloc] initWithString:@"  " attributes:@{NSAttachmentAttributeName : doubleArrowIcon, NSBaselineOffsetAttributeName : @(-2)}]];
[self.nextButton setAttributedTitle:attrButtonTitle forState:UIControlStateNormal];

Note: I would post images to illustrate if I could, but I do not have the minimum stack overflow reputation to do so.

I'm still unsure why the above code does not display images on iOS8 devices when compiled with the 7.1 SDK, but I have found a workaround. I tried out different initialization methods for NSMutableAttributedString that has a text attachment until I got something that did the job. Code below:

NSTextAttachment *doubleArrowIcon = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
doubleArrowIcon.image = [UIImage imageNamed:@"double-arrows"];

NSAttributedString *textAttachment = [NSAttributedString attributedStringWithAttachment:doubleArrowIcon];

NSMutableAttributedString *mutableTextAttachment = [[NSMutableAttributedString alloc] initWithAttributedString:textAttachment];
[mutableTextAttachment addAttribute:NSBaselineOffsetAttributeName value:[NSNumber numberWithInt:-2] range:NSMakeRange(0, [textAttachment length])  ];
[attrButtonTitle appendAttributedString:mutableTextAttachment];

If your image is still not showing after the good initialization, it is a problem with the lineBreakMode of your label/Text. The image cannot be/ must not be cut by the lineBreak.

just add

yourlabel.text.lineBreakMode = NSLineBreakByClipping;

To your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM