Make specified text in NSTextView Bold - objective-c

I am using a little bit of code to change the text in an NSTextView
NSString *string = #"This is a title\n\nThis is some info";
[content setString:string];
I would like to make the text "This is a title" the only text that is bold when displaying in the NSTextView and the rest normal text. Is there any way to do this? Maybe like how the StackOverflow editor works? __bold text here__
Thanks in advance!

I'm not sure if you can just apply boldness as that's usually part of another set of glyphs. But how's this work...
NSString* textUnattributed = #"This is a title\n\nThis is some info";
NSMutableAttributedString* textAttributed = [[NSMutableAttributedString alloc] initWithString:textUnattributed];
[textAttributed addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"HelveticaNeue-Bold" size:16.0]
range:[textUnattributed rangeOfString:#"This is a title"]];
content.attributedText = textAttributed;

Related

Objective c UIFont systemFontOfSize does not work

I am trying to change text font size with using NSAttributedString. But it's size doesn't change.
NSDictionary *attrDict = #{NSFontAttributeName : [UIFont boldSystemFontOfSize:22], NSForegroundColorAttributeName : [UIColor orangeColor]};
NSAttributedString *newAttString = [[NSAttributedString alloc] initWithString:mytext attributes:attrDict];
[result appendAttributedString:newAttString];
Only text color changes. Size of result string is not 22 and also it is not bold.
Instead of applying the attributes with the alloc, init, try doing it after with something like (with a mutable NSAttributedString):
NSMutableAttributedString *newAtt = [[NSMutableAttributedString alloc] initWithString:mytext]; // Allocate a new NSMutableAttributedString with `mytext`
[newAtt addAttributes:#{NSFontAttributeName : [UIFont boldSystemFontOfSize:20],
NSForegroundColorAttributeName: [UIColor orangeColor]}
range:NSMakeRange(0, [result length])]; // add new attributes for the length of the string `mytext`
[result setAttributedText:newAtt];
This answer would vary depending on what result is, I tested it on a UITextView and it worked fine, there is also an attributedText
property on UILabels.
Hope this helps.
You didn't mention what result means at the end of your code. Are you sure you want to "append" it?
Besides, I use this code for setting fonts
[UIFont fontWithName:#"Arial-BoldMT" size:22.0f]
This can be used to set different fonts and sizes respectively.
Hope this helps:)

NSTextStorage - How to find return chars (new line) in a text

In an NSTextStorage I insert time strings at the current pointer location like this :
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: #"00:00:00"];
[attrString autorelease];
int pos = [self selectedRange].location;
[[self textStorage] insertAttributedString: attrString atIndex:pos];
So far so good, it works perfect. But now I want to position the pointer at the beginning of the next line. Obviously this is right after the next return char.
Now how to find the next return char in textStorage and position the pointer there ?
I have not found any hint in the web for this task. Please help ...
You won't find a method to set the cursor (more precise: selection with zero length) in NSTextStorage's API, because it is a storage, having no selection. The selection is a property of the text view. This is the result of MVC. Simply do a check: You can have many text views displaying the same text. Obviously each one needs its own selection.
What you have to do is to get the position of the next paragraph (this is better than searching for \n) and set this as a selection for the text view.
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: #"00:00:00"];
[attrString autorelease]; // You should *really* use ARC
int pos = [self selectedRange].location;
[[self textStorage] insertAttributedString: attrString atIndex:pos];
// Get the next paragraph
NSString *text = self.textStorage.string;
NSRange restOfStringRange = NSMakeRange( pos, [text length]-pos );
NSUInteger nextParagraphIndex;
// You have to look to the start of the next paragraph
[text getParagraphStart:&nextParagraphIndex end:NULL contentsEnd:NULL forRange:restOfStringRange];
NSTextView *view = self.textView; // Or where ever you get it from
view.selectedRange = NSMakeRange(nextParagraphIndex, 0);
Typed in Safari, not tested, just to show the basic approach.

Handling UIContentSizeCategoryDidChangeNotification for NSAttributedString in UITextView

I have an NSAttributedString in a UITextView and would like to handle the UIContentSizeCategoryDidChangeNotification when working with Dynamic Type and specifically the text styles. All the examples I've seen (IntroToTextKitDemo) address the case where the font is the same for the whole UI element. Does anyone know how to handle this properly so all the attributes update properly?
Note: I asked this on the developer forums when iOS 7 was under NDA. I'm posting it here because I found a solution and thought others might find it useful.
I found a solution. When handling the notification you need to walk the attributes and look for the text styles and update the font:
- (void)preferredContentSizeChanged:(NSNotification *)aNotification
{
UITextView *textView = <the text view holding your attributed text>
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
NSRange range = NSMakeRange(0, attributedString.length - 1);
// Walk the string's attributes
[attributedString enumerateAttributesInRange:range options:NSAttributedStringEnumerationReverse usingBlock:
^(NSDictionary *attributes, NSRange range, BOOL *stop) {
// Find the font descriptor which is based on the old font size change
NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
UIFont *font = mutableAttributes[#"NSFont"];
UIFontDescriptor *fontDescriptor = font.fontDescriptor;
// Get the text style and get a new font descriptor based on the style and update font size
id styleAttribute = [fontDescriptor objectForKey:UIFontDescriptorTextStyleAttribute];
UIFontDescriptor *newFontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:styleAttribute];
// Get the new font from the new font descriptor and update the font attribute over the range
UIFont *newFont = [UIFont fontWithDescriptor:newFontDescriptor size:0.0];
[attributedString addAttribute:NSFontAttributeName value:newFont range:range];
}];
textView.attributedText = attributedString;
}

Change font for string with object in Objective C

I am bringing in some data from a JSON file and I want to change the font to courier but when I try to do the following I get this error: "Property 'font' not found on object NSString". Is there any way around this?
NSString *timePeriod = [diction objectForKey:#"Time Period"];
UIFont *changeFont = [UIFont fontWithName:#"Courier" size:12];
timePeriod.font = changeFont;
A font is part of an attributed string.
NSMutableAttributedString timeSringWithAttr = [[NSMutableAttributedString alloc] initWithString:timeString];
[timeStringWithAttr addAttribute:NSFontAttributeName
value:changeFont
range:NSRangeFromString(timeString)];
NSString just stores strings, it has no knowledge of fonts. If you want to set the font when you draw the string use the NSString AppKit additions:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSString_AppKitAdditions/Reference/Reference.html#//apple_ref/doc/uid/20000155
Basically, you want to set the font when you draw the string to screen.
The NSString class doesn't have font property, and it shouldn't since every String object is an array of characters.
Instead, use UILabel or UITextView, depends on your needs with text in it, and set font property on them.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
label.text = #"YOUR_TEXT";
label.font = [UIFont fontWithName:#"Courier" size:12.0f];
And in convention you shouldn't name variables with verb names, those are for functions.
Like UIFont *changeFont..

Displaying NSMutableAttributedString

I have the below code in my app
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:self.myDisplayTxt];
[string addAttribute:(NSString*)kCTForegroundColorAttributeName
value:(id)[[UIColor redColor] CGColor]
range:NSMakeRange(0,5)];
self.myTextView.text = string;
When assigning the NSMutableAttributedString to UITextView I get the following error:
Incompatible objective c types struct NSMutableAttributedString
expected struct nsstring
So please let me know, how can I display the NSMutableAttributedString in UITextView.
You can try to use some library to do that. As omz wrote, the UITextView does not unfortunatelly support the NSAttributedString.
Maybe this one can help you: https://github.com/enormego/EGOTextView
They say about this library the following:
UITextView replacement with additional support for NSAttributedString.
UPDATE: Based on your clarification in the comment for omz's answer, you can look here:
Underline text inside uitextview
UPDATE 2: In iOS 6 you can use the NSAttributedString out of the box. For example like this:
UIColor *_red=[UIColor redColor];
UIFont *font=[UIFont fontWithName:#"Helvetica-Bold" size:72.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:-3.0] range:NSMakeRange(0, _stringLength)];
You can't, UITextView doesn't support attributed strings. If you really only want to use attributed strings to set the foreground color (as in your example), you could achieve the same by setting the text view's textColor property.
You should assign attributed string via UITextView.attributedText property. UITextView.text accepts NSString or plain text only.
textView.attributedText = attributedString;
See documentation:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextView_Class/index.html#//apple_ref/occ/instp/UITextView/attributedText