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

北慕城南 提交于 2019-12-13 00:44:58

问题


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.


回答1:


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];



回答2:


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



来源:https://stackoverflow.com/questions/26006267/nstextattachment-image-not-displayed-on-ios-8-devices-with-ios7-1-sdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!