Select Bold and Italicized text from textField - ios

How can I select only bold and italicized text entered by user in a textField/textView ?
We can make a selected text bold, italicized, underline and any combination of these three but what about its vice-versa.
*This is not specific to Mac OSX or iOS, solution in either one is good for me.
EDIT:
I tried by reading the text in attributed string as :
NSAttributedString *string=self.textView.string;
But as textView and textField returns NSString so all formatting is gone.

on iOS use attributedText properties with labels/textfields
on OSX use attributedStringValue
you can then enumerate through the attributedText's attributes and check each attribute. Ill whip up some code (osx & iOS)
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:#"none "];
id temp = [[NSAttributedString alloc] initWithString:#"bold " attributes:#{NSFontAttributeName: [UIFont boldSystemFontOfSize:12]}];
[str appendAttributedString:temp];
temp = [[NSAttributedString alloc] initWithString:#"italic " attributes:#{NSFontAttributeName: [UIFont italicSystemFontOfSize:12]}];
[str appendAttributedString:temp];
temp = [[NSAttributedString alloc] initWithString:#"none " attributes:#{NSFontAttributeName: [UIFont systemFontOfSize:12]}];
[str appendAttributedString:temp];
temp = [[NSAttributedString alloc] initWithString:#"bold2 " attributes:#{NSFontAttributeName: [UIFont boldSystemFontOfSize:12]}];
[str appendAttributedString:temp];
self.label.attributedText = str;
NSMutableString *italics = [NSMutableString string];
NSMutableString *bolds = [NSMutableString string];
NSMutableString *normals = [NSMutableString string];
for (int i=0; i<str.length; i++) {
//could be tuned: MOSTLY by taking into account the effective range and not checking 1 per 1
//warn: == might work now but maybe i'd be cooler to check font traits using CoreText
UIFont *font = [str attribute:NSFontAttributeName atIndex:i effectiveRange:nil];
if(font == [UIFont italicSystemFontOfSize:12]) {
[italics appendString:[[str mutableString] substringWithRange:NSMakeRange(i, 1)]];
} else if(font == [UIFont boldSystemFontOfSize:12]){
[bolds appendString:[[str mutableString] substringWithRange:NSMakeRange(i, 1)]];
} else {
[normals appendString:[[str mutableString] substringWithRange:NSMakeRange(i, 1)]];
}
}
NSLog(#"%#", italics);
NSLog(#"%#", bolds);
NSLog(#"%#", normals);
Now here is how to find it. Deducing a selection range from this should be easy peasy :)
Note: you can only have a continuous selection! neither on osx nor on ios can you select n parts of a textfield/textview

Related

Attributed string color- Objective-c

I have a display like in the picture
Im getting this from a string str which is like below
Code I have tried
lbl1.text=newStr;
NSString *textxtra = #"Xtra";
NSString *textremove = #"Remove";
NSMutableAttributedString *attrsString = [[NSMutableAttributedString alloc] initWithAttributedString:lbl1.attributedText];
// search for word occurrence
NSRange range = [lbl1.text rangeOfString:textxtra];
NSRange range1 = [lbl1.text rangeOfString:textremove];
if (range.location != NSNotFound) {
[attrsString addAttribute:NSForegroundColorAttributeName value:[UIColor systemGreenColor] range:range];
}
if (range1.location != NSNotFound) {
[attrsString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range1];
}
// set attributed text
lbl1.attributedText = attrsString;
How to get the string before Xtra (American Cheese) and after Xtra($1) in green color ?
The part before Remove(House Mayo) in red color?
i.e The whole string American Cheese: Xtra $1 should be in green color.
I get the idea to take the string in between \n.
i.e string before Xtra upto \n and after Xtra upto \n
But couldn't understand exactly how to implement
Any ideas/suggestions will be helpful
Not tested, but this should do the trick:
NSString *initialSting = #"";
NSArray *lines = [initialSting componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *attributedLines = [[NSMutableArray alloc] init];
NSDictionary *redAttributes = #{};
NSDictionary *greenAttributes = #{};
for (NSString *aLine in lines)
{
NSAttributedString *aLineAttributedString;
//Here, you could also check, that the string is like "someString: Xtra someOtherString", because if Xtra is misplaced...
if ([aLine containsString:#"Xtra"])
{
aLineAttributedString = [[NSAttributedString alloc] initWithString:aLine attributes:greenAttributes];
//Here, you could also check, that the string is like "someString: Remove someOtherString", because if Remove is misplaced...
}
else if ([aLine containsString:#"Remove"])
{
aLineAttributedString = [[NSAttributedString alloc] initWithString:aLine attributes:redAttributes];
}
else
{
aLineAttributedString = [[NSAttributedString alloc] initWithString:aLine];
}
[attributedLines addObject:aLineAttributedString];
}
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
NSAttributedString *newLine = [[NSAttributedString alloc] initWithString:#"\n"];
if ([attributedLines count] > 0)
{
for (NSUInteger i = 0; i < [attributedLines count] - 1; i++)
{
[attributedString appendAttributedString:attributedLines[i]];
[attributedString appendAttributedString:newLine];
}
[attributedString appendAttributedString:[attributedLines lastObject]];
}
The logic:
Get an array of NSString for each line with componentsSeparatedByCharactersInSet:
Create an array of NSAttributedString, that will be populated for each line.
For each line, color it if needed, then add it to the array.
Finally, there is no componentsJoinedByString: for NSAttributedString, so do a manual for loop to reconstruct the final NSAttributedString.

Bolding an nsstring

I have looked online for ways to bold a NSString and either it's not there or I can't seem to find it. I simply want to bold the word in the NSString but so far, what I have done is not woking:
NSString *player1Name = [[UIFont boldSystemFontOfSize:12] fontName];
I have relied on this to make "player1Name" bold but it doesn't work at all.
When I run it I get this:
Thanks in advance to anyone who helps me figure out the solution.
You can not bold a NSString... Try a NSAttributedString...
NSAttributedString *player1Name = [[NSAttributedString alloc] initWithString:#"name" attributes:#{NSFontAttributeName : [UIFont boldSystemFontOfSize:12]}];
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/
fontName is a property on UIFont
[[UIFont boldSystemFontOfSize:12] fontName]
returns the font name HelveticaNeueInterface-MediumP4
Try this:
NSString *myString = #"My string!";
NSAttributedString *myBoldString = [[NSAttributedString alloc] initWithString:myString
attributes:#{ NSFontAttributeName: [UIFont boldSystemFontOfSize:35.0] }];
Also you can set range for particular text like:
NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = ...;
NSRange boldedRange = NSMakeRange(2, 4);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
[attrString beginEditing];
[attrString addAttribute:kCTFontAttributeName
value:boldFontName
range:boldedRange];
[attrString endEditing];
You can't make NSString bold. Instead of that you can make UILabel text into bold. Because UILabels are for UI representation & NSStrings are just objects. So make your UILabel bold
[infoLabel setFont:[UIFont boldSystemFontOfSize:16]];

Cannot set underline for UILabel [duplicate]

This question already has answers here:
How to make an underlined text in UILabel?
(7 answers)
Closed 4 years ago.
I have a UILabel which have text: "Something here and privacy policy", I just want to create underline for the text privacy policy but the code not affect. If I create underline for full text of my label then it worked, but it's not what I want.Here is my code:
NSString *str = self.myLabel.text;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
NSRange index = [str rangeOfString:#"privacy policy"];
if (index.location != NSNotFound){
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(index.location, index.length)];
//if I change index.location by 0 then it worked,
//with the underline start at the begin text of mylabel but that not what I expected
[self.myLabel setAttributedText:attributedString];
}
Is have something wrong with my code(my app support for iOS 7 and latter)?
Please try this piece of code.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 250, 40)];
label.font=[UIFont fontWithName:#"Helvetica" size:12];
label.textColor=[UIColor blackColor];
NSString *text = #"Something and Privacy Policy";
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc ]initWithString:text];
NSInteger location = [#"Something and " length]-1;
NSInteger length = [#"Privacy Policy" length];
[attrString addAttribute:NSUnderlineStyleAttributeName value:#(NSUnderlineStyleSingle) range:NSMakeRange(location, length)];
label.attributedText=attrString;
[self.view addSubview:label];
To temporarily fix your issue, you can split your String into 2 NSMutableAttributedString with latter string having text "privacy policy". You can then underline the whole text and concatenate the two strings.
NSString *str = self.myLabel.text;
NSRange index = [str rangeOfString:#"privacy policy"];
if (index.location != NSNotFound){
NSString *tempString = [str substringWithRange:NSMakeRange(0, index.location - 1)];
NSAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:tempString];
NSString *privacyString=[str substringFromIndex:index.location];
NSAttributedString *attributedString1 = [[NSMutableAttributedString alloc] initWithString:privacyString];
[attributedString1 addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, attributedString1.length)];
//with the underline start at the begin text of mylabel but that not what I expected
NSMutableAttributedString *mutableAttString = [[NSMutableAttributedString alloc] init];
[mutableAttString appendAttributedString: attributedString];
[mutableAttString appendAttributedString:attributedString1];
[self.myLabel setAttributedText:mutableAttString];
}
The best way I've found to underline a portion of a text is to use Interface Builder (Designer first, coder second). Granted this might not be what you want but for a temporary solution I propose the following:
Instructions
1) Place a UILabel in your viewController of choice and add constraints as needed.
2) Click on your label, replace the text and go to Attributes Inspector. (Image 1)
3) Change your UILabel from 'Plain Text' to 'Attributed'
4) Highlight the portion you want underlined as shown in Image 2 below and press the 'T' in a square.
5) On the toolbar of the window that shows up, you'll see an underlined 'T'. Select 'single' (Image 3).
Images

Replace the truncation ellipsis of UILabel in iOS 7

How can I replace the truncation ellipsis ("…") of a UILabel in iOS 7 with another attributed character? For example, with a colored ">".
I was hoping Text Kit's NSLayoutManager would make this possible, but it appears UILabel doesn't make it public if it uses it.
Also, can I safely assume that an ellipsis is used as the truncation character in every localisation? Maybe different languages have different truncation characters.
I recommend you use TTTAttributedLabel, just set property "attributedTruncationToken" to your custom string.
I don't think it gives you access to this. I think you would have do handle it manually. For example, use TextKit to determine the size of your string, if it doesn't fit in the available area, truncate it yourself and append a ">" and then put your new string in the label.
NSAttributedString has methods for getting the size of the string.
Let me know if you need any more detail on this..?
I think you can do some customization in -replaceElipsesForLabel method provided by Fonix to get your desired result.
I have written a method to do it, and works in iOS7
-(void)setCustomEllipsis:(NSString*)customEllipsis inLabel:(UILabel*)label with:(NSString*)string{
//Replace the ellipsis
NSMutableString* result = [[NSMutableString alloc] initWithString:#""];
NSArray* strings = [string componentsSeparatedByString:#" "];
for (NSString* s in strings) {
CGRect newSize = [[NSString stringWithFormat:#"%#%#%#",result,s,customEllipsis] boundingRectWithSize:CGSizeMake(label.frame.size.width,0) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:label.font} context:nil];
if (newSize.size.height < label.frame.size.height) {
[result appendString:s];
[result appendString:#" "];
}else{
[result appendString:customEllipsis];
break;
}
}
[label setText:result];
//Set different font to the ellipsis
const CGFloat fontSize = 13;
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
UIColor *foregroundColor = [UIColor lightGrayColor];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:regularFont, NSFontAttributeName,foregroundColor, NSForegroundColorAttributeName, nil];
NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:boldFont, NSFontAttributeName, nil];
const NSRange range = [label.text rangeOfString:customEllipsis];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:result
attributes:attrs];
[attributedText setAttributes:subAttrs range:range];
[label setAttributedText:attributedText];
}

How to show multiple line text that has different font without using multiple Labels

I have to show a text paragraph that contains few words in bold font. ex.
If I use different labels then on changing the orientation it does not resize properly.
Can anyone tell me what can the best way to do it.
You can use an UITextView using NSAttributedString (have a look to the apple doc)
And you have an explanation of how to use it here.
You can find the range of your word and change the font or the color or whatever using :
- (IBAction)colorWord:(id)sender {
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSArray *words = [self.text.text componentsSeparatedByString:#" "];
for (NSString *word in words)
{
if ([word hasPrefix:#"#"])
{
NSRange range=[self.text.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
}
}
[self.text setAttributedText:string];
}
You have to use a NSAttributedString and assign it to the UITextField, this is an example:
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
NSMutableAttributedString *myAttributedString = [[NSMutableAttributedString alloc] initWithString:yourString];
[myAttributedString addAttribute:NSFontAttributeName
value:boldFont
range:NSMakeRange(0, 2)];
[myAttributedString addAttribute:NSFontAttributeName
value:regularFont
range:NSMakeRange(3, 5)];
[self.description setAttributedText:myAttributedString];
Find all the doc here:
NSAttributedString
For your case, you can use a webView and load it with your string:
[webView loadHTMLString:[NSString stringWithFormat:#"<html><body style=\"background-color: transparent;\">This is <b><i>Test</b></i> dummy text ..</body></html>"] baseURL:nil];

Resources