Have multiple ranges with different attributes on NSAttributedString - ios

I have a multiline UILabel of which I would like to increase the line height, but I also want part of it to be a different color, only the line height works fine. But as soon as I try to change the color for a certain range it just goes back to the stock appearance, no line either..
Anyone a tip? This is done in the content setter.
- (void)setContent:(NSString *)content {
_content = content;
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.content];
NSMutableAttributedString *mutableAttrString = [attributedString mutableCopy];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineSpacing: 5.0f];
NSDictionary *attributes = #{
NSFontAttributeName: [UIFont fontWithName:#"BentonSans-Regular" size:16.0],
NSParagraphStyleAttributeName: paragraphStyle
};
NSDictionary *colorAttributes = #{
NSForegroundColorAttributeName: [UIColor redColor]
};
[mutableAttrString addAttributes:attributes range:NSRangeFromString(self.content)];
[mutableAttrString addAttributes:colorAttributes range:NSMakeRange(4, 8)];
[self.label setAttributedText: mutableAttrString];
}
Thanks!

The NSRangeFromString function expects a string like #"{3,10}". In other words, it expects a string that contains two numbers that specify the starting location and length of the range. I suspect that the content string isn't a string like that.
So this line
[mutableAttrString addAttributes:attributes range:NSRangeFromString(self.content)];
should be
[mutableAttrString addAttributes:attributes range:NSMakeRange(0,mutableAttrString.length)];

in your viewdidLoad Method assign string to self.content :
self.content = #"pass your text ";
// Remove the First line of your method it is not needed
- (void)setContent:(NSString *)content {
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.content];
NSMutableAttributedString *mutableAttrString = [attributedString mutableCopy];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineSpacing: 5.0f];
NSDictionary *attributes = #{
NSFontAttributeName: [UIFont fontWithName:#"BentonSans-Regular" size:16.0],
NSParagraphStyleAttributeName: paragraphStyle
};
NSDictionary *colorAttributes = #{
NSForegroundColorAttributeName: [UIColor redColor]
};
[mutableAttrString addAttributes:attributes range:NSRangeFromString(self.content)];
[mutableAttrString addAttributes:colorAttributes range:NSMakeRange(4, 8)];
[self.label setAttributedText: mutableAttrString];
}

Related

Intrinsic content size of UILabel with NSAttributedString and indentation

Why does setting an indent on the paragraph style attribute not have an affect on a UILabel using NSAttributedString?
For example:
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.firstLineHeadIndent = 50;
NSDictionary *attributes = #{
NSForegroundColorAttributeName : [UIColor redColor],
NSParagraphStyleAttributeName : paragraphStyle,
};
NSString *string = #"some string";
self.label.attributedText = [[NSAttributedString alloc] initWithString:string
attributes:attributes];
UILabel with indentation (green background set to see the label size):
UILabel without indentation (green background set to see the label size):

How can I show the text with different fonts in textView in ios?

Hi I am doing one application. In that I need to show text in different fonts. I mean if I show name in one font and I show city name in different font.
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 200, 100)];
textView.text = #"Vijay Apple Dev";
NSString *textViewText = textView.text;
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:textViewText];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Courier" size:20]
range:[textViewText rangeOfString:#"Apple"]];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Verdana" size:20]
range:[textViewText rangeOfString:#"Vijay"]];
textView.attributedText = attributedText;
[self.view addSubview:textView];
Try to do like this one... And customize according to your requirement like font name and font size
NSString *firstName = #"FirstName";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:firstName];
UIFont *font = [UIFont fontWithName:#"Helvetica" size:20];
[attributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, firstName.length)];// Here define your range.
textView.attributedText = attributedString;
//Use attributed String
//Apply properties to both strings
//then merge and set it to textview
NSString *selectedString=#"Hey,";
UIFont *fontSelectedText = [UIFont boldSystemFontOfSize:25];
NSDictionary *dictBoldSelectedText = [NSDictionary dictionaryWithObjectsAndKeys:fontSelectedText, NSFontAttributeName, nil];
NSMutableAttributedString *mutAttrTextViewSelectedString = [[NSMutableAttributedString alloc] initWithString:selectedString];
[mutAttrTextViewSelectedString setAttributes:dictBoldSelectedText range:NSMakeRange(0,selectedString.length)];
[_tTextView setAttributedText:mutAttrTextViewSelectedString];
//Second String
NSString *restOfStrig=#"\nHello";
NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:restOfStrig];
UIFont *fontText = [UIFont boldSystemFontOfSize:16];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
[mutAttrTextViewString setAttributes:dictBoldText range:NSMakeRange(0,restOfStrig.length)];
//Combining both the Attributed String
[mutAttrTextViewSelectedString appendAttributedString:mutAttrTextViewString];
NSMutableAttributedString * finalAttributedStr=[[NSMutableAttributedString alloc] initWithAttributedString:mutAttrTextViewSelectedString];
//setting it to the textView
[_tTextView setAttributedText:finalAttributedStr];
Use NSAttributedString
An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string. The cluster’s two public classes, NSAttributedString and NSMutableAttributedString, declare the programmatic interface for read-only attributed strings and modifiable attributed strings, respectively.
NSAttributedString
When you create your attributed string, then just set it to your textView:
self.textView.attributedText = myAttributedString;

iOS 6 multiline label line spacing

There is a problem with line spacing in UILabel, I am using custom font and when I use smilies there is no space between two lines. which obviously looks not so good. So I used this code for line spacing but app crashes giving the error
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSAttributedString invalid for autoresizing, it must have a single spanning paragraph style (or none) with a non-wrapping lineBreakMode.'
if ([cell.label2 respondsToSelector:#selector(setAttributedText:)])
{
UIFont *font =btMyriadProRegularWithSize14Pt;
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineSpacing: 22];
NSDictionary *attributes = #{ NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle };
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:chatMessage.msgString attributes:attributes];
[cell.label2 setAttributedText: attributedString];
}
else
{
NSString * msg = [NSString stringWithFormat:#"%#: %#",chatMessage.from,chatMessage.msgString];
cell.label2.text = msg;
}
try this
[cell.label2 setAdjustsFontSizeToFitWidth:NO];
maybe even only for iOS6
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) { //*
[cell.label2 setAdjustsFontSizeToFitWidth:NO];
}
detect iOS 6 as decribed here: https://developer.apple.com/library/ios/documentation/userexperience/conceptual/transitionguide/SupportingEarlieriOS.html
Set up Attributable String
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
[paragraph setLineBreakMode:NSLineBreakByWordWrapping];
[paragraph setLineBreakMode:NSLineBreakByTruncatingTail];
self.attrText = [[NSMutableAttributedString alloc] initWithString:text];
[self.attrText addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, text.length)];
self.Text = text;

align text using drawInRect:withAttributes:

In the iOS 5 version of my app I had:
[self.text drawInRect: stringRect
withFont: [UIFont fontWithName: #"Courier" size: kCellFontSize]
lineBreakMode: NSLineBreakByTruncatingTail
alignment: NSTextAlignmentRight];
I'm upgrading for iOS 7. The above method is deprecated. I'm now using drawInRect:withAttributes:. The attributes parameter is an NSDictionary object. I can get drawInRect:withAttributes: to work for the former font parameter using this:
UIFont *font = [UIFont fontWithName: #"Courier" size: kCellFontSize];
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: font, NSFontAttributeName,
nil];
[self.text drawInRect: stringRect
withAttributes: dictionary];
What key-value pairs do I add to dictionary to get NSLineBreakByTruncatingTail and NSTextAlignmentRight?
There is one key to set the paragraph style of the text (including line breaking mode, text alignment, and more).
From docs:
NSParagraphStyleAttributeName
The value of this attribute is an NSParagraphStyle object. Use this attribute to apply multiple attributes to a range of text. If you do not specify this attribute, the string uses the default paragraph attributes, as returned by the defaultParagraphStyle method of NSParagraphStyle.
So, you can try the following:
UIFont *font = [UIFont fontWithName:#"Courier" size:kCellFontSize];
/// Make a copy of the default paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
/// Set text alignment
paragraphStyle.alignment = NSTextAlignmentRight;
NSDictionary *attributes = #{ NSFontAttributeName: font,
NSParagraphStyleAttributeName: paragraphStyle };
[text drawInRect:rect withAttributes:attributes];
The code is going that way:
CGRect textRect = CGRectMake(x, y, length-x, maxFontSize);
UIFont *font = [UIFont fontWithName:#"Courier" size:maxFontSize];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
paragraphStyle.alignment = NSTextAlignmentRight;
NSDictionary *attributes = #{ NSFontAttributeName: font,
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: [UIColor whiteColor]};
[text drawInRect:textRect withAttributes:attributes];

Increasing the font size of first letter in UILabel.text

I would like the first letter of the UILabel to have a different font size from others, a few font size larger. Need some guidance on how to do it. The label has a lot of words.
This is what I have tried:
NSArray * words = [Label.text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *firstLetter = [[words objectAtIndex:0] substringToIndex:1];
But got stuck in increasing the size of the NSString. Is there a better way? I am welcome to suggestions and guidance.. Thanks..
EDIT:
[Label setFont:[UIFont fontWithName:#"Arial" size:12.f]];
NSArray * words = [Label.text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
UIFont *fontFirst=[UIFont fontWithName:#"Arial" size:15.f];
NSDictionary *attrsDictFirst=[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
NSAttributedString *finalString=[[NSAttributedString alloc] initWithString:[[words objectAtIndex:0] substringToIndex:1] attributes:attrsDictFirst];
To get, for example, this:
Say this:
NSString* s2 = #"Fourscore and seven years ago, our fathers brought forth "
#"upon this continent a new nation, conceived in liberty and dedicated "
#"to the proposition that all men are created equal.";
NSMutableAttributedString* content2 =
[[NSMutableAttributedString alloc]
initWithString:s2
attributes:
#{
NSFontAttributeName:
[UIFont fontWithName:#"HoeflerText-Black" size:16]
}];
[content2 setAttributes:
#{
NSFontAttributeName:[UIFont fontWithName:#"HoeflerText-Black" size:24]
} range:NSMakeRange(0,1)];
[content2 addAttributes:
#{
NSKernAttributeName:#-4
} range:NSMakeRange(0,1)];
NSMutableParagraphStyle* para2 = [NSMutableParagraphStyle new];
para2.headIndent = 10;
para2.firstLineHeadIndent = 10;
para2.tailIndent = -10;
para2.lineBreakMode = NSLineBreakByWordWrapping;
para2.alignment = NSTextAlignmentJustified;
para2.lineHeightMultiple = 1.2;
para2.hyphenationFactor = 1.0;
[content2 addAttribute:NSParagraphStyleAttributeName
value:para2 range:NSMakeRange(0,1)];
Then assign content2 to a label's attributedText.
Need to use NSAttributedString. iOS6.0 onwards
After getting the first letter make put it into attributed string, change its size.
take rest of the string set other size.
UIFont *font=[UIFont fontWithName:#"Arial" size:12.f];
NSDictionary *attrsDict=[NSDictionary dictionaryWithObject:font
forKey:NSFontAttributeName];
NSAttributedString *attribString=[[NSAttributedString alloc] initWithString:[words[0] substringFromIndex:1] attributes:attrsDict];
UIFont *fontFirst=[UIFont fontWithName:#"Arial" size:15.f];
NSDictionary *attrsDictFirst=[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
NSAttributedString *firstString=[[NSAttributedString alloc] initWithString:[attribString subStringToIndex:1] attributes:attrsDictFirst];
[attribString replaceCharactersInRange:NSMakeRange(0, 1) withString:firstString];

Resources