UILabel: Custom underline color? - ios

I need the text of a UILabel to be black, but have a light gray underline under the text. Is this possible with NSAttributedString or TTTAttributedLabel? Or is custom drawing using Core Graphics needed?
CLARIFICATION:
I need a specific color text on a different color underline. Example: blue text on red underline.

You can do with NSAttributedString as below.
NSMutableAttributedString* string = [[NSMutableAttributedString alloc]initWithString:#"you string"];
[string addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, string.length)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, string.length)];//TextColor
[string addAttribute:NSUnderlineStyleAttributeName value:underlineNumber range:NSMakeRange(0, string.length)];//Underline color
[string addAttribute:NSUnderlineColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, string.length)];//TextColor
yourlabel. attributedText = string;
Note: You can also underline particular range of string as like in this post. Also note down, it works ios6+ only.

Instead of creating a local NSMutableAttributedString and adding attributes one by one, we can always create multiple attributes in one single line (using NSDictionary symbols - # { } ) to a specific UILabel including the actual text.
Objective C:
[someUILabel setAttributedText:
[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#", [someObject stringProperty]]
attributes:#{NSUnderlineStyleAttributeName:#(NSUnderlineStyleThick),
NSUnderlineColorAttributeName:[[UIColor alloc] initWithRed:0.953f green:0.424f blue:0.416f alpha:1.00f]}]];
In the above example we have set an underline which is also bold - total 2 attributes.
Swift:
self.someUIButton.setAttributedTitle(NSAttributedString(string: "UIButtonStringTitle", attributes: [NSUnderlineStyleAttributeName : 1]), forState: .Normal)

// Print `str` in black, and underline the word STRING in gray.
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:#"This is my STRING"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, str.length-7)];
[str addAttribute:NSUnderlineColorAttributeName value:[UIColor grayColor] range:NSMakeRange([str length]-6, 6)];
[str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange([str length]-6, 6)];
_label.attributedText = str; // assuming you have an iVar name `label`

NSAttributedString *title;
title = [[NSAttributedString alloc] initWithString:#"iphone app" for NSAttributedString" attributes:#{ NSFontAttributeName : [UIFont fontWithName:#"Noteworthy-Bold" size:36], NSUnderlineStyleAttributeName : #1 , NSStrokeColorAttributeName : [UIColor blackColor]}];
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)];
label.attributedText = title;
[self.view addSubview:label];

m-farhan.com farhan will be underlined
//-----------------------------
// Create attributed string
//-----------------------------
NSString *str = #"m-Farhan.com";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
// Add attribute NSUnderlineStyleAttributeName
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(2, 4)];
// Set background color for entire range
[attributedString addAttribute:NSBackgroundColorAttributeName
value:[UIColor colorWithRed:0.103 green:0.305 blue:0.492 alpha:1.000]
range:NSMakeRange(0, [attributedString length])];
// Define label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 280, 80)];
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextAlignment:UITextAlignmentLeft];
// Set label text to attributed string
[label setAttributedText:attributedString];
[[self view] addSubview:label];

In swift, use NSAttributedString.Key.underlineColor.

Related

How to bold some words in my UITextView using NSMutableAttributedString?

I have a UITextView and there are certain words I'm casting with NSString stringWithFormat that I'd like to be bolded.
I have looked around Stack Overflow and tried to follow the the postings but I guess I'm not understanding it.
Here's what I've been playing around with:
NSRange boldedRange = NSMakeRange(0, 4);
NSString *boldFontName = [[UIFont fontWithName:#"Helvetica-Bold" size:100]fontName];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self.name];
[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName
value:boldFontName
range:boldedRange];
[attrString endEditing];
self.resultsTextView.attributedText = attrString;
self.resultsTextView.text = [NSString stringWithFormat:#"One day, %# was taking a walk and saw a %# boy. He was %# a %#.", attrString, self.adjective, self.adverb, self.noun];
You can also set it the following way if you want by setting a dictionary as a whole, as attribute
NSString *strTextView = #"This is some demo Text to set BOLD";
NSRange rangeBold = [strTextView rangeOfString:#"BOLD"];
UIFont *fontText = [UIFont boldSystemFontOfSize:10];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:strTextView];
[mutAttrTextViewString setAttributes:dictBoldText range:rangeBold];
[textViewTermsPolicy setAttributedText:mutAttrTextViewString];
Use the below code to set Attribute string in TextView.
NSString *infoString =#"I am Kirit Modi from Deesa.";
NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];
UIFont *font_regular=[UIFont fontWithName:#"Helvetica" size:20.0f];
UIFont *font_bold=[UIFont fontWithName:#"Helvetica-Bold" size:20.0f];
[attString addAttribute:NSFontAttributeName value:font_regular range:NSMakeRange(0, 4)];
[attString addAttribute:NSFontAttributeName value:font_bold range:NSMakeRange(5, 15)];
[attString addAttribute:NSFontAttributeName value:font_regular range:NSMakeRange(16, infoString.length - 15 - 1)];
[self.txtView setAttributedText:attString];
OutPut :
Check out #CrazyYoghurt improvement on #Bbrame and #BenoitJadinon on this previous SO question 3586871
I've been using it for over a year and it works great. One limitation: I don't think you can bold multiple times the same string if it appears more than once in your original string. But you can probably expend the code to make it do so if you wish.
If you also need to filter some word from the UITextView and make it underline/change color of that particular text only then you can use the below code.
Here, I'm getting all the doc text in the Content string and filter some particular text that is in Hebrew language.
NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc]initWithString:content attributes:nil];
[aStr addAttribute:NSLinkAttributeName value:#"http://www.apple.com" range:[content rangeOfString:#"מדיניות פרטיות"]];
[aStr addAttribute:NSLinkAttributeName value:#"http://www.google.com" range:[content rangeOfString:#"לינק"]];
textview.linkTextAttributes = #{NSUnderlineStyleAttributeName : #(NSUnderlineStyleSingle)};
textview.delegate = (id)self;
//...You can as per your custom color
[aStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[content rangeOfString:#"מדיניות פרטיות"]];
[aStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[content rangeOfString:#"לינק"]];
//Here You can also add the tap gesture on that text.
//Tap gesture
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tappedTextView:)];
[textview addGestureRecognizer:tapRecognizer];
[textview setAttributedText:aStr];
textview.textAlignment=NSTextAlignmentRight;
//For getting the text location in the tap gesture
-(void)tappedTextView:(UITapGestureRecognizer *)tapGesture
{
UITextView *textView = (UITextView *)tapGesture.view;
CGPoint tapLocation = [tapGesture locationInView:textView];
UITextPosition *textPosition = [textView closestPositionToPoint:tapLocation];
NSDictionary *attributes = [textView textStylingAtPosition:textPosition inDirection:UITextStorageDirectionForward];
NSString *urlStr = attributes[NSLinkAttributeName];
if (urlStr)
{
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",url]]];
PrivacyViewController *next = [PrivacyViewController new];
[self.navigationController pushViewController:next animated:YES];
}
}

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

Make the character smaller than others and at the bottom right in NSString iOS

I want to make the string as
I used this code but it always show the '%' at the top right.
UIFont *PercentFont = [UIFont fontWithName:#"System" size:30];
NSString* percentString =[NSString stringWithFormat:#"%d%%",value ];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:percentString attributes:#{NSFontAttributeName: PercentFont}];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:240/255.0 green:133/255.0 blue:105/255.0 alpha:1.0] range:NSMakeRange(0, percentString.length -1)];
[attributedString setAttributes:#{NSFontAttributeName : [UIFont fontWithName:#"System" size:17] ,NSBaselineOffsetAttributeName : #17} range:NSMakeRange(percentString.length -1, 1)];
// set % digit color
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:240/255.0 green:133/255.0 blue:105/255.0 alpha:1.0] range:NSMakeRange(percentString.length -1, 1)];
Please help to correct it. Thanks in advance.
Change your code for this:
UIFont *PercentFont = [UIFont systemFontOfSize:30];
NSString* percentString =[NSString stringWithFormat:#"%d%%",9];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:percentString attributes:#{NSFontAttributeName: PercentFont}];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:240/255.0 green:133/255.0 blue:105/255.0 alpha:1.0] range:NSMakeRange(0, percentString.length -1)];
[attributedString setAttributes:#{NSFontAttributeName : [UIFont systemFontOfSize:17] ,NSBaselineOffsetAttributeName : #-2} range:NSMakeRange(percentString.length -1, 1)];
// set % digit color
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:240/255.0 green:133/255.0 blue:105/255.0 alpha:1.0] range:NSMakeRange(percentString.length -1, 1)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(120, 100, 200, 100)];
label.attributedText =attributedString;
It will be good idea change PercentFont by percentFont (lower case).

Comparing 2 of the same NSAttributedStrings not working

Why does comparing the same NSAttributedString not work?
I have the following:
- (void)someSetupClass {
NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:#"abcdefghijklmnopqrstuvwxyz"];
[aString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[aString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"HelveticaNeue-Light" size:(16.0)] range:NSMakeRange(0, 20)];
[aString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
_aTextView.attributedText = aString;
_aTextView.delegate = self;
[_scroll addSubview:_best];
}
- (void)textViewDidBeginEditing:(UITextView *)textView {
NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:#"abcdefghijklmnopqrstuvwxyz"];
[aString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[aString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"HelveticaNeue-Light" size:(16.0)] range:NSMakeRange(0, 20)];
[aString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
if ([textView.attributedText isEqualToAttributedString:aString]) {
// Never reaches here, but why?
textView.text = #"";
// textView.textColor = [UIColor blackColor];
}
[textView becomeFirstResponder];
}
Make that textview strongly typed variable and try. Eg.
#property(nonatomic, strong)UITextView * aTextView;
Check if your textView has default font set to Helvetica/system - size 12. May be because of this last part of your attributed string is taking default font of the textView after you setText. But part of aString (uvwxyz) does not have font assigned and hence it mismatches.
Hope this helps you :)

Button title color

I want to set button title with underline and of browncolor:
For that I am doing:
NSMutableAttributedString *nearestLocation = [[NSMutableAttributedString alloc] initWithString:#"Locate Manually"];
[nearestLocation addAttribute:(NSString*)kCTUnderlineStyleAttributeName
value:[NSNumber numberWithInt:NSUnderlineStyleSingle]
range:(NSRange){0,[nearestLocation length]}];
[btn_manually setAttributedTitle:nearestLocation forState:UIControlStateNormal];
[btn_manually setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
It is displaying underline but not browncolor.
Try to use like this....
[nearestLocation addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:NSMakeRange(0,[nearestLocation length])];
In iOS, NSAttributedString is used modifying the text, you can use "NSMutableAttributedString" for multi color text, font, style, etc using single UIButton or UILabel.
NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:#"The Underlined text"];
// making text property to underline text-
[titleString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [titleString length])];
// using text on button
[btn_manually setAttributedTitle: titleString forState:UIControlStateNormal];
btn_manually.titleLabel.textColor = [UIColor brownColor];
NSString *tempString=#"your string";
NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:tempString];
int lenght=(int)[tempString length];
[attString addAttribute:(id)NSForegroundColorAttributeName value:[UIColor brownColor] range:NSMakeRange(0,lenght)];
[attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:2] range:NSMakeRange(0, length)];
UIButton *hyperLinkButton=[UIButton buttonWithType:UIButtonTypeCustom];
hyperLinkButton.frame=CGRectMake(30, 5, 100, 30);
[hyperLinkButton setAttributedTitle:attString forState:UIControlStateNormal];
hyperLinkButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
hyperLinkButton.tag=[[[[[[personalDetailDictionary objectForKey:#"Acknowledgements"] objectForKey:#"details"] objectAtIndex:i] objectForKey:#"tagValue"] objectForKey:#"text"] intValue];
[hyperLinkButton addTarget:self action:#selector(hyperLinkAction:) forControlEvents:UIControlEventTouchUpInside];
hyperLinkButton.titleLabel.textAlignment=NSTextAlignmentLeft;
[self.view addSubview:hyperLinkButton];

Resources