iOS: Bold and Italic on the same word - iphone

Background: I have been trying to display a sentence with Bold and Italic font as well as normal ones.
Question: How can I display something like this "Hello, my name is Byte". Notice that Byte is both bold and italic, while other words remains normal.
I have tried: I think coreText should be able to do something along the line, I just have not been able to find the correct way to do it. I also used TTTAttributeLabel and cannot make it both bold and italic. I have Three20 loaded, just do not know which or what to use. Webview does not work with my background.
As a reply to Carles Estevadeordal:
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(10, 360, 300, 40)];
[webView setBackgroundColor: [UIColor clearColor]];
[webView loadHTMLString:[NSString stringWithFormat:#"<html><body style=\"background-color: transparent;\">Hello, my name is <b><i>Byte</b></i></body></html>"] baseURL:nil];
[self.view addSubview:webView];
This is exactly the code, I used. It displayed white background.

After a good night sleep, I found a way to do it using TTTAtributedlabel.
Here is how:
TTTAttributedLabel *attLabel = [[TTTAttributedLabel alloc]initWithFrame:CGRectMake(x, y, xx, yy)];
NSString *text = #"Hello, my name is Byte";
[attLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^(NSMutableAttributedString *mutableAttributedString) {
//font helvetica with bold and italic
UIFont *boldSystemFont = [UIFont fontWithName:#"Helvetica-BoldOblique" size:10];
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
NSRange boldRange = [[mutableAttributedString string] rangeOfString:#"Byte" options:NSCaseInsensitiveSearch];
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:boldRange];
CFRelease(font);
return mutableAttributedString;
}];
I still do not have a way to add 2 attributes (ie: bold and italic separately) into the same word/letter. But this does the trick.

In case you are still interested in a CoreText solution to this issue :
newFont = CTFontCreateCopyWithSymbolicTraits(fontRef,
self.textSize,
NULL,
kCTFontBoldTrait | kCTFontItalicTrait,
kCTFontBoldTrait | kCTFontItalicTrait);
[attrString addAttribute:(NSString*)kCTFontAttributeName
value:(id)newFont
range:[copyString rangeOfString:customText.text]];

You can use this where sender is instance of UIButton
sender.titleLabel.font=[UIFont fontWithName:#"Helvetica-BoldOblique" size:18.0f];

To add two attributes (this is non ARC code):
#define kLabelFontSize 16.0
NSString labelString = #"Let's slide loudly";
[self.tttLabel setText:labelString afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:kLabelFontSize];
CTFontRef boldFont = CTFontCreateWithName((CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
if (boldFont) {
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(id)boldFont range:NSMakeRange(6, 11)];
CFRelease(boldFont);
}
UIFont *italicSystemFont = [UIFont italicSystemFontOfSize:kLabelFontSize];
CTFontRef italicFont = CTFontCreateWithName((CFStringRef)boldSystemFont.fontName, italicSystemFont.pointSize, NULL);
if (italicFont) {
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(id)italicFont range:NSMakeRange(12, 18)];
CFRelease(italicFont);
}
}];
return mutableAttributedString;
}];

If the sentence has a fixed format the easiest solution is to use 2 different UILabels, one with the normal font and the other one with a Bold and Italic font set.
If the sentence is dynamic then you should use a UIWebView object as it was a lavel and load a simple webpage with your text and the < b > < i > < /i > < /b > fields set at the spot when you want it bold and italic like:
[myWebViewLabel loadHTMLString:[NSString stringWithFormat:#"<html><body style=\"background-color: transparent;\">Hello, my name is <b><i>Byte</b></i></body></html>"] baseURL:nil];
I hope it helps.

Related

UITextView - setting font size of attributedText slow?

I'm trying to change the font size of my UITextView's text, which is using attributed text, with the following:
UIFont *font = [self.textView.font fontWithSize:value];
NSDictionary *attributes = #{ NSFontAttributeName: font };
NSMutableAttributedString *attrString = [self.textView.attributedText mutableCopy];
[attrString addAttributes:attributes range:NSMakeRange(0, attrString.length)];
self.textView.attributedText = attrString;
However, using this in combination with a slider causes a noticeable slow down. Am I doing this correctly? Simple setting the font size of the textView.font property did not work.
This is how I'm setting the attributed text in the first place:
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:#"Neutra church-key brunch farm-to-table disrupt skateboard, bushwick next level organic gentrify street art. Pop-up echo park pork belly pour-over. Bespoke meggings put a bird on it, plaid hashtag farm-to-table YOLO freegan pug pickled jean shorts quinoa gentrify forage. Tumblr butcher echo park, small batch mumblecore banjo trust fund intelligentsia bushwick VHS raw denim."];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(59, 13)];
[string addAttribute:(NSString*)NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:(NSRange){59, 13}];
textView.attributedText = string;

iPhone : Font is not affecting to UI

I'm using Constantia font family in my app, regular bold and italic style is my requirement, the problem I am facing is, I can only get output of regular style, and not the bold and italic, I've already added all three styled fonts into app, and in plist file under Fonts provided by application section. I tried with following
UIFont *bFont = [UIFont fontWithName:#"Constantia-Bold" size:24.0];
UIFont *bFont = [UIFont fontWithName:#"ConstantiaBold" size:24.0];
UIFont *bFont = [UIFont fontWithName:#"Constantia_Bold" size:24.0];
UIFont *iFont = [UIFont fontWithName:#"Constantia-Italic" size:24.0];
UIFont *iFont = [UIFont fontWithName:#"ConstantiaItalic" size:24.0];
UIFont *iFont = [UIFont fontWithName:#"Constantia_Italic" size:24.0];
but not a single case is working, only UIFont *font = [UIFont fontWithName:#"Constantia" size:24.0]; is working. I know that I'm missing something in font name only.
I tried find font into Mac font's option, I got this font under All Fonts section (left top), one strange this I found is, all Constantia bold, italic and regular are installed as a single name, i.e. Constantia only.
P.S. Fonts can be downloaded from here.
This is Step for, How to add custom font in Application.
1 - Add .TTF font in your application
2 - Modify the application-info.plist file.
3 - Add the key "Fonts provided by application" to a new row
4 - and add each .TTF file (of font) to each line.
For more info read This and This site.
For Bold
// Equivalent to [UIFont fontWithName:#"FontName-BoldMT" size:17]
UIFont* font = [UIFont fontWithFamilyName:#"FontName" traits:GSBoldFontMask size:17];
And bold/italic
UIFont* font = [UIFont fontWithMarkupDescription:#"font-family: FontName; font-size: 17px; font-weight: bold/italic;"]; // set here, either bold/italic.
Here is how you can see the real name of every font available for use by your app:
// Log fonts
for (NSString *family in [UIFont familyNames])
{
NSLog(#"Font family %#:", family);
for (NSString *font in [UIFont fontNamesForFamilyName:family])
NSLog(" %#", font);
}
UPDATE 16 June 2018: application can be rejected, try find another solution
#import <dlfcn.h>
// includer for font
NSUInteger loadFonts( )
{
NSUInteger newFontCount = 0;
NSBundle *frameworkBundle = [NSBundle bundleWithIdentifier:#"com.apple.GraphicsServices"];
const char *frameworkPath = [[frameworkBundle executablePath] UTF8String];
if (frameworkPath)
{
void *graphicsServices = dlopen(frameworkPath, RTLD_NOLOAD | RTLD_LAZY);
if (graphicsServices)
{
BOOL (*GSFontAddFromFile)(const char *) = dlsym(graphicsServices, "GSFontAddFromFile");
if (GSFontAddFromFile)
{
BOOL verizon = NO;
NSLog(#"%#",[[UIDevice currentDevice] machine]);
if ([[[UIDevice currentDevice] machine] rangeOfString:#"iPhone3,3"].location != NSNotFound) {
verizon = YES;
}
for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:#"ttf" inDirectory:nil])
{
if ([fontFile rangeOfString:#"_"].location != NSNotFound && verizon) {
newFontCount += GSFontAddFromFile([fontFile UTF8String]);
}
if ([fontFile rangeOfString:#"-"].location != NSNotFound && !verizon) {
newFontCount += GSFontAddFromFile([fontFile UTF8String]);
}
}
}
}
}
return newFontCount;
}
I'm using the function usually :)
I don't think such type of font is exist in IOS. Please check from here http://iosfonts.com/

UILabels not overlaying correctly in UITextView

I'm trying to add syntax highlighting to my program.I'm using this code to add highlights:
-(void)highlightWord:(NSString *)word: (UIColor *)color {
int amount = textDisplay.text.length;
NSString *newString = textDisplay.text;
NSUInteger count = 0, length = amount;
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [textDisplay.text rangeOfString: word options:NSLiteralSearch range:range];
if(range.location != NSNotFound)
{
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}
while (count != 0) {
count--;
NSRange highlight = [newString rangeOfString:word];
newString = [textDisplay.text stringByReplacingCharactersInRange:highlight withString:#" "];
UILabel *view1 = [[UILabel alloc] initWithFrame:[self frameOfTextRange:highlight inTextView:textDisplay]];
view1.text = word;
view1.textColor = color;
view1.font = [UIFont fontWithName:#"System" size: 14.0];
view1.backgroundColor = [UIColor clearColor];
view1.textAlignment = UITextAlignmentLeft;
[textDisplay addSubview:view1];
}
}
- (IBAction)highlighString:(id)sender {
for (UIView *subview in [textDisplay subviews]){
if ([subview isKindOfClass:[UILabel class]]){
[subview removeFromSuperview];
}
}
[self highlightWord:#"test" :[UIColor blueColor]];
[self highlightWord:#"this" :[UIColor redColor]];
[self highlightWord:#"is" :[UIColor grayColor]];
[self highlightWord:#"a" :[UIColor greenColor]];
}
#end
But this seems to cause a weird results:
The desired result would be that it overlays to colored label seamlessly.
Mixing UILabel and UITextView is unlikely to give you easy copy and paste. It's an interesting idea, but I'd be surprised if it worked seamlessly. The usual Apple solution for this problem in all non-beta versions of iOS is to use a UIWebView, horrible as that is. Cocoanetics has one called DTRichTextEditor which I haven't reviewed, but based on the quality of their work on DTCoreText (which I'm very impressed with), I have high hopes for it for iOS 5. Betas are under NDA, but you may be interested in watching Session 220 from WWDC 2012 for more future-looking information.
Your specific bug is that you're adding the labels as subviews to the text view. You should put them on top of the text view as peers. Putting them inside the textview makes you subject the text view's drawing system, which is biting you. Of course when you put them on top of the text view, that's going to make it hard to handle copy and paste. You'll need to pass the touches through somehow, and then draw the selection correctly. See the previous paragraph.
If a fully editable rich-text view were easy to hack up with some labels, then you'd find several implementations on GitHub. Unfortunately it's actually pretty tough to do well. I bow to Cocoanetics for taking it on; I gave up pretty quickly. If you can simplify your problem to a non-general text view, then it may be possible this way, but I'd recommend investigating DTRichTextEditor or a UIWebView. See Session 511 "Rich Text Editing in Safari on iOS" from WWDC 2011.

UIFont fontWithName font name

Say you want a specific font for UIFont.
How do you know what it's called?
E.g. if you wanted to use this code:
[someUILabelObject setFont:[UIFont fontWithName:#"American Typewriter" size:18]];
From where do you copy the exact phrase "American Typewriter". Is there a header file in Xcode?
UPDATE
Also found this handy.
Might be interesting for you as Quick Win within the Debugger:
(lldb) po [UIFont fontNamesForFamilyName:#"Helvetica Neue"]
(id) $1 = 0x079d8670 <__NSCFArray 0x79d8670>(
HelveticaNeue-Bold,
HelveticaNeue-CondensedBlack,
HelveticaNeue-Medium,
HelveticaNeue,
HelveticaNeue-Light,
HelveticaNeue-CondensedBold,
HelveticaNeue-LightItalic,
HelveticaNeue-UltraLightItalic,
HelveticaNeue-UltraLight,
HelveticaNeue-BoldItalic,
HelveticaNeue-Italic
)
November 2018 - Update
A new swift-y reference for "Custom Fonts with Xcode" - by Chris Ching. I had to update, as this is a great value posting for the new way combined with all missing parts to use custom fonts in a project.
The documentation for UIFont is pretty clear on this:
You can use the fontNamesForFamilyName: method to retrieve the
specific font names for a given font family.
(Note: It is a class method)
You can get the family names like this:
NSArray *familyNames = [UIFont familyNames];
Try
NSArray *familyNames = [UIFont familyNames];
[familyNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
NSLog(#"* %#",obj);
NSArray *fontNames = [UIFont fontNamesForFamilyName:obj];
[fontNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
NSLog(#"--- %#",obj);
}];
}];
label.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:17];
I made a library to solve this problem:
https://github.com/Nirma/UIFontComplete
All fonts are represented as a system Font enum and the library also details a way of using it with your custom fonts in the read me.
Basically this:
let font = UIFont(name: "Arial-BoldItalicMT", size: 12.0)
Is replaced with either this:
let font = UIFont(font: .arialBoldItalicMT, size: 12.0)
Or this:
let myFont = Font.helvetica.of(size: 12.0)
This is how you get all font names in your project. That's it ... 3 lines of code
NSArray *fontFamilies = [UIFont familyNames];
for (int i=0; i<[fontFamilies count]; i++)
{
NSLog(#"Font: %# ...", [fontFamilies objectAtIndex:i]);
}

How change font of uilabel?

I want to change the font of label. And font which i am using is shown in image.
How use it in my application. I have already add in .plist as show in image. But it not working proper. How i manage it?
Thanks in advances...
Use this to set the font programmatically:
[TheLabelName setFont:[UIFont fontWithName:#"American Typewriter" size:18]];
Custom fonts in IOS
to set an label font just
yourLabel.font = [UIFont fontWithName:#"CloisterBlack" size:64.0];
If you want to use the standard font, then just as usually: you can set it in the interface builder for this label or programmatically for this label.
If you want to apply your custom font (according to the image you want that), then you can do smth. like
UIFont *font = [UIFont fontWithName:#"MyFont" size:20];
[label setFont:font];
Also you can explore this ref:
Can I embed a custom font in an iPhone application?
it might be useful in your case.
Add your custom font file .ttf in resourse and use every time when you want to display formatted font like
headLbl.font = [UIFont fontWithName:#"Museo-700" size:20.f];
Add a font in your resource directory like this image that you have already done now main thing you cann't wirte the name of the font that you have added as it is check my image font having name ROCKB.ttf but i have write the Rockwell-Bold so you have to check by what name it has been installed in your code then pick the name from there and then put that name in lable the font will reflect the label now.
label.font = [UIFont fontWithName:#"Rockwell-Bold" size:20];
and font family by this code NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
for (indFamily=0; indFamily<[familyNames count]; ++indFamily)
{
NSLog(#"Family name: %#", [familyNames objectAtIndex:indFamily]);
fontNames = [[NSArray alloc] initWithArray:
[UIFont fontNamesForFamilyName:
[familyNames objectAtIndex:indFamily]]];
for (indFont=0; indFont<[fontNames count]; ++indFont)
{
NSLog(#" Font name: %#", [fontNames objectAtIndex:indFont]);
}
[fontNames release];
}
[familyNames release];