iOS FontAwesome in middle of another string

不问归期 提交于 2019-12-07 05:13:25

问题


I am trying to display some text and an icon inside a single string using FontAwesome.

Here is what I have:

NSString *icon = [NSString fontAwesomeIconStringForIconIdentifier:@"icon-map-marker"];

NSString *locationString = [NSString stringWithFormat:@"%@ %@", icon, otherNormalString];

Basically I want to have the map marker show up in front of the location being displayed. Using FontAwesome should make this really simple but I can't quite get it to work right.

Here is also what shows up if I NSLog the string icon:

Any idea on how I can properly accomplish this?


回答1:


Strings do not carry any style information (including font). In order to include font information, you'll need to make an NSAttributedString. All this -fontAwesomeIconStringForIconIdentifier method is doing is returning a unicode value given an identifier.

On the assumption that you're using ios-fontawesome, you'd want to do something like:

... your locationString assignment ...
NSMutableAttributedString *astring = [[NSMutableAttributedString alloc] initWithString:locationString];

[astring addAttribute:NSFontAttributeName 
                value:[UIFont iconicFontOfSize:size] 
                range:NSMakeRange(0,1)]; // The first character

You can then assign the attributed string to a label's attributedText property, or similarly display it.



来源:https://stackoverflow.com/questions/20894697/ios-fontawesome-in-middle-of-another-string

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