Can I set the `attributedText` property of `UILabel` - ios

Can I set the attributedText property of a UILabel object? I tried the below code:
UILabel *label = [[UILabel alloc] init];
label.attributedText = #"asdf";
But it gives this error:
Property "attributedText" not found on object of type 'UILabel *'
#import <CoreText/CoreText.h> not working

Here is a complete example of how to use an attributed text on a label:
NSString *redText = #"red text";
NSString *greenText = #"green text";
NSString *purpleBoldText = #"purple bold text";
NSString *text = [NSString stringWithFormat:#"Here are %#, %# and %#",
redText,
greenText,
purpleBoldText];
// If attributed text is supported (iOS6+)
if ([self.label respondsToSelector:#selector(setAttributedText:)]) {
// Define general attributes for the entire text
NSDictionary *attribs = #{
NSForegroundColorAttributeName: self.label.textColor,
NSFontAttributeName: self.label.font
};
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:text
attributes:attribs];
// Red text attributes
UIColor *redColor = [UIColor redColor];
NSRange redTextRange = [text rangeOfString:redText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:#{NSForegroundColorAttributeName:redColor}
range:redTextRange];
// Green text attributes
UIColor *greenColor = [UIColor greenColor];
NSRange greenTextRange = [text rangeOfString:greenText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:#{NSForegroundColorAttributeName:greenColor}
range:greenTextRange];
// Purple and bold text attributes
UIColor *purpleColor = [UIColor purpleColor];
UIFont *boldFont = [UIFont boldSystemFontOfSize:self.label.font.pointSize];
NSRange purpleBoldTextRange = [text rangeOfString:purpleBoldText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:#{NSForegroundColorAttributeName:purpleColor,
NSFontAttributeName:boldFont}
range:purpleBoldTextRange];
self.label.attributedText = attributedText;
}
// If attributed text is NOT supported (iOS5-)
else {
self.label.text = text;
}

Unfortunately, UILabel doesn't support attributed strings. You can use OHAttributedLabel instead.
Update: Since iOS6, UILabel does support attributed strings. See UILabel reference or Michael Kessler's answer below for more details.

NSString *str1 = #"Hi Hello, this is plain text in red";
NSString *cardName = #"This is bold text in blue";
NSString *text = [NSString stringWithFormat:#"%#\n%#",str1,cardName];
// Define general attributes for the entire text
NSDictionary *attribs = #{
NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:12]
};
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attribs];
UIFont *boldFont = [UIFont fontWithName:#"Helvetica-Bold" size:14.0];
NSRange range = [text rangeOfString:cardName];
[attributedText setAttributes:#{NSForegroundColorAttributeName: [UIColor blueColor],
NSFontAttributeName:boldFont} range:range];
myLabel = [[UILabel alloc] initWithFrame:CGRectZero];
myLabel.attributedText = attributedText;

for Swift 4:
iOS 11 and xcode 9.4
let str = "This is a string which will shortly be modified into AtrributedString"
var attStr = NSMutableAttributedString.init(string: str)
attStr.addAttribute(.font,
value: UIFont.init(name: "AppleSDGothicNeo-Bold", size: 15) ?? "font not found",
range: NSRange.init(location: 0, length: str.count))
self.textLabel.attributedText = attStr

For people using swift, here's a one-liner:
myLabel.attributedText = NSMutableAttributedString(string: myLabel.text!, attributes: [NSFontAttributeName:UIFont(name: "YourFont", size: 12), NSForegroundColorAttributeName: UIColor.whiteColor()])

so,here is the code to have different properties for sub strings ,of a string.
NSString *str=#"10 people likes this";
NSString *str2=#"likes this";
if ([str hasSuffix:str2])
{
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:str];
// for string 1 //
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,str.length-str2.length)];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(0,str.length-str2.length)];
// for string 2 //
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange((str.length-str2.length),str2.length)];
[string addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:12] range:NSMakeRange((str.length-str2.length),str2.length)];
label.attributedText=string;
}
else
{
label.text =str;
}

Hope this helps ;)
NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:#"asdf"];
[attrStr setFont:[UIFont systemFontOfSize:12]];
[attrStr setTextColor:[UIColor grayColor]];
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
lbl.attributedText = attrStr;

UIFont *font = [UIFont boldSystemFontOfSize:12];
NSDictionary *fontDict = [NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:#" v 1.2.55" attributes: fontDict];
UIFont *fontNew = [UIFont boldSystemFontOfSize:17];
NSDictionary *fontDictNew = [NSDictionary dictionaryWithObject: fontNew forKey:NSFontAttributeName];
NSMutableAttributedString *attrStringNew = [[NSMutableAttributedString alloc] initWithString:#“Application” attributes: fontDictNew];
[attrStringNew appendAttributedString: attrString];
self.vsersionLabel.attributedText = attrStringNew;

Related

How to set NSMutableAttributedString into two lines

I want to create a single UILablel like this.
I want to set year font to HElvaticaNeu-medium and the 2015 into HelvaticaNeu. And I need these two strings to appear in 2 lines just like in this image.
How I can do this. I set two seperate NSMutableAttributedString in this way.
UIFont *helMedium = [UIFont fontWithName:#"HelveticaNeue-Medium" size:12.0];
NSDictionary *mediumDict = [NSDictionary dictionaryWithObject: helMedium forKey:NSFontAttributeName];
NSMutableAttributedString *mAttrString = [[NSMutableAttributedString alloc] initWithString:#"Year :" attributes: mediumDict];
UIFont *helNormal = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
NSDictionary *normalDict = [NSDictionary dictionaryWithObject: helNormal forKey:NSFontAttributeName];
NSMutableAttributedString *nAttrString = [[NSMutableAttributedString alloc] initWithString:#"2016" attributes: normalDict];
Now how should I set this 2 strings in two lines?
Does anyone have an idea?
you need to append the second string to first string
Use this code.
UIFont *helMedium = [UIFont fontWithName:#"HelveticaNeue-Medium" size:12.0];
NSDictionary *mediumDict = [NSDictionary dictionaryWithObject: helMedium forKey:NSFontAttributeName];
NSMutableAttributedString *mAttrString = [[NSMutableAttributedString alloc] initWithString:#"Year :" attributes: mediumDict];
UIFont *helNormal = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
NSDictionary *normalDict = [NSDictionary dictionaryWithObject: helNormal forKey:NSFontAttributeName];
NSMutableAttributedString *nAttrString = [[NSMutableAttributedString alloc] initWithString:#"\n2016" attributes: normalDict];
[mAttrString appendAttributedString:nAttrString];
label.attributedText = mAttrString;
NSMutableAttributedString *nAttrString = [[NSMutableAttributedString alloc] initWithString:#"\n2016" attributes: normalDict];
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
[attString appendAttributedString: mAttrString];
[attString appendAttributedString: nAttrString];
// label.attributedText = attString
UIFont *helMedium = [UIFont fontWithName:#"HelveticaNeue-Medium" size:12.0];
NSDictionary *mediumDict = [NSDictionary dictionaryWithObject: helMedium forKey:NSFontAttributeName];
NSMutableAttributedString *mAttrString = [[NSMutableAttributedString alloc] initWithString:#"Year :" attributes: mediumDict];
UIFont *helNormal = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
NSDictionary *normalDict = [NSDictionary dictionaryWithObject: helNormal forKey:NSFontAttributeName];
NSMutableAttributedString *nAttrString = [[NSMutableAttributedString alloc] initWithString:#"\n2016" attributes: normalDict];
[mAttrString appendAttributedString:nAttrString];
_yearLabel.attributedText = mAttrString;
[_yearLabel setNumberOfLines:2];
If you want more space around text in UILabel, specify width and height constraints for the same.

Apply text colour and subscript to NSMutableString in objective-c

I am unable to apply both the attributes at the same. Either only color or subscript am able to apply.
Here is my code
NSMutableAttributedString * attributedText = [[NSMutableAttributedString alloc]initWithString:#"some text"];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Lato-Bold" size:16]
range:NSMakeRange(14,1)];
[attributedText addAttribute:(NSString *)kCTSuperscriptAttributeName value:#-1 range:NSMakeRange(14,1)];
[attributedText addAttribute:(NSString *)kCTForegroundColorAttributeName value:#{ NSForegroundColorAttributeName : [UIColor colorWithRed:85.0/255.0 green:38.0/255.0 blue:152.0/255.0 alpha:1.0] } range:(NSRange){0,6}];
You can try with this code
[str addAttribute:(NSString *)kCTSuperscriptAttributeName value:#-1 range:NSMakeRange(14,1)];
[str setAttributes:#{NSForegroundColorAttributeName:[UIColor greenColor]}
range:(NSRange){0,7}];
Here is an update for your code workable.
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(20, 100, 200, 44)];
[self.view addSubview:textView];
UIColor *color = [UIColor colorWithRed:85.0/255.0 green:38.0/255.0 blue:152.0/255.0 alpha:1.0];
UIFont *font = [UIFont fontWithName:#"Arial" size:20.0];
NSMutableAttributedString * attributedText = [[NSMutableAttributedString alloc]initWithString:#"some text"];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Arial" size:16]//Lato-Bold, Your font name crahes
range:NSMakeRange(8,1)];//x(8) is start index,y(1) is length from start index x(8)
NSDictionary *attrs = #{NSForegroundColorAttributeName : color,NSFontAttributeName:font};
[attributedText addAttributes:attrs range:NSMakeRange(0,6)];//start index start from 0, and length start counting from 1
//[attributedText addAttribute:(NSString *)kCTSuperscriptAttributeName value:#-1 range:NSMakeRange(14,1)];
textView.attributedText = attributedText;
OR
You can try with this.
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(20, 100, 200, 44)];
NSString *newsTitle = #"Hello";
NSString *sportTtle = #"World";
NSString *title = [NSString stringWithFormat:#"%# %#", newsTitle,sportTtle];
textView.text = title;
UIColor *color = [UIColor redColor];
UIFont *font = [UIFont fontWithName:#"Arial" size:20.0];
NSDictionary *attrs = #{NSForegroundColorAttributeName : color,NSFontAttributeName:font};
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
[attrStr addAttributes:attrs range:[textView.text rangeOfString:sportTtle]];
textView.attributedText = attrStr;
[self.view addSubview:textView];

Does iOS support spannable strings?

Is there any support for spannable string in iOS?
I would like to create an underlineSpan and on click of it and then open some other view controller.
NSAttributedString *title;
title = [[NSAttributedString alloc] initWithString:#"hello how r u..." attributes:#{ NSFontAttributeName : [UIFont fontWithName:#"Noteworthy-Bold" size:15], NSUnderlineStyleAttributeName : #1 , NSStrokeColorAttributeName : [UIColor blackColor]}]; //1
UILabel *label;
label = [[UILabel alloc] initWithFrame:CGRectMake( (self.view.bounds.size.width - title.size.width) / 2.0f, 40.0f, title.size.width, title.size.height)]; //2
label.attributedText = title; //3
[self.view addSubview:label];
Yes, they are called NSAttributedStrings in iOS.
Example Code to Add underline
NSString *str = #"Amit";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, 4)];
More info # Apple Documentation
To add link to that underline you check out this code:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:#"Google Webpage"];
[attributedString addAttribute:NSLinkAttributeName
value:#"http://www.google.com"
range:[[attributedString string] rangeOfString:#"Google Webpage"]];
NSDictionary *linkAttributes = #{NSForegroundColorAttributeName: [UIColor greenColor],
NSUnderlineColorAttributeName: [UIColor lightGrayColor],
NSUnderlineStyleAttributeName: #(NSUnderlinePatternSolid)};
// assume that textView is a UITextView previously created (either by code or Interface Builder)
textView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;
textView.delegate = self;
This source code was found # Raywenderlich website

Bold a part of title, iOS 7

I have read several method about bolding a part of string.
But I still can't get it work.
Here's my code
#define FONT_OPEN_BOLD(s) [UIFont fontWithName:#"OpenSans-Bold" size:s]
In viewDidLoad function
NSString *stringName = #"ShowTimes" ;
UIFont *font = FONT_OPEN_BOLD(15.0f);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:stringName];
[attrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, 4)];
self.title = stringName;
Any suggestion?
Thank you in advance. ^^
NSString *stringName = #"ShowTimes" ;
UIFont *font = FONT_OPEN_BOLD(15.0f);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:stringName];
[attrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, 4)];
//Initialize TTAttributedLabel with rect
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 150)];
//Set the attributedText property of TTAttributedLabel
label.attributedText = attrString;
//Set navigationItem.titleView to the label view we've created
self.navigationItem.titleView = label;
What you could do is use an NSAttributedString.
NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = ...;
NSRange boldedRange = NSMakeRange(22, 4);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
[attrString beginEditing];
[attrString addAttribute:kCTFontAttributeName
value:boldFontName
range:boldedRange];
[attrString endEditing];
//draw attrString here...
Take a look at this handy dandy guide to drawing NSAttributedString objects with Core Text.

UIRefreshControl attributedTitle multiple lines

Is it possible to use multiple lines in the UIRefreshControl title? Whenever I add \n to the NSAttributedString only the first line will be displayed. I'm trying to set a title and on the next line some more text. So is there a workaround to use two lines of text in the UIRefreshControl?
This is the current code where only "Title Here" is displayed:
self.refreshControl = [[UIRefreshControl alloc] init];
NSString *title = #"Title Here";
NSString *subText = #"Subtext Here";
NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#\n%#",title,subText]];
[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica" size:20.0f] range:NSMakeRange(0, [title length])];
[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica" size:14.0f] range:NSMakeRange([title length],[subText length])];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, [title length])];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange([title length], [subText length])];
self.refreshControl.attributedTitle = attString;
here is a tricky method: find the UILabel in the UIRefreshControl and set numberOfLines = 0.
UILabel *titleLabel = [[[[self.refreshControl subviews] firstObject] subviews] lastObject];
if (titleLabel) {
titleLabel.numberOfLines = 0;
NSString title = #"Pull to Refresh.\nUpdated Time: 09:30"; // \n for new line.
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:title];
}
This piece of code will work
NSString *title = #"Title Here";
NSString *subText = #"Subtext Here";
NSMutableAttributedString *titleAttString = [[NSMutableAttributedString alloc] initWithString:title];
NSMutableAttributedString *subTitleAttString = [[NSMutableAttributedString alloc] initWithString:subText];
[titleAttString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica" size:20.0f] range:NSMakeRange(0, [title length])];
[subTitleAttString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica" size:14.0f] range:NSMakeRange(0,[subTitle length])];
[titleAttString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, [title length])];
[subTitleAttString addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, [subTitle length])];
[titleAttString appendAttributedString:subTitleAttString];
self.refreshControl.attributedTitle = titleAttString;
The trick is to change the UILable's property of Refresh Controller to Zero.
The hack is we have to find the label through the subviews and there child as shown below.
Here is a Swift version
if let refreshLabel = refreshControl?.subviews.first?.subviews.last as? UILabel {
refreshLabel.numberOfLines = 0
}
So here is the full code sample
private var marketRefreshController = UIRefreshControl()
private var lastUpdatedDate = Date()
override func viewDidLoad() {
super.viewDidLoad()
tableView.refreshControl = marketRefreshController
if let refreshLabel = refreshControl?.subviews.first?.subviews.last as? UILabel {
refreshLabel.numberOfLines = 0
}
marketRefreshController.addTarget(self, action: #selector(refreshMarketData), for: .valueChanged)
marketRefreshController.tintColor = UIColor.blue
let textAttributes = [NSAttributedString.Key.font: UIFont.appSubTitle,
NSAttributedString.Key.foregroundColor: UIColor.blue]
let timeSinceLastUpdate = lastUpdatedDate.timeAgoSinceNow // Date Sting Converter Helper Method
let displayString = "Fetching Market Data ... \n Last Updated: \(timeSinceLastUpdate)"
marketRefreshController.attributedTitle = NSAttributedString(string: displayString,
attributes: textAttributes)
tableView.addSubview(marketRefreshController)
}
The expected output should be like -

Resources