How do I use HTML.fromhtml in IOS? - ios

I want to make a NSString notification like this: "You must pay 4.00 dollar.".The money has a red color.In Android ,I can use HTML.formhtml do it.But I don't know how to do it in IOS.Who can help me?

try this code
CATextLayer *aTextLayer_= [[[CATextLayer alloc]init] autorelease];
aTextLayer_.frame = CGRectMake(10, 100, 300, 50);
aTextLayer_.backgroundColor=[UIColor clearColor].CGColor;
aTextLayer_.foregroundColor = [[UIColor redColor] CGColor];
aTextLayer_.alignmentMode=kCAAlignmentCenter;
aTextLayer_.contentsScale = [[UIScreen mainScreen] scale];
aTextLayer_ .wrapped=YES;
[aTextLayer_ setAlignmentMode:kCAAlignmentLeft];
UIFont *smallFont = [UIFont systemFontOfSize:25];
CTFontRef ctSmallFont = CTFontCreateWithName((CFStringRef)smallFont.fontName, smallFont.pointSize, NULL);
UIFont *boldFont = [UIFont systemFontOfSize:25];
CTFontRef ctBoldFont = CTFontCreateWithName((CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
CGColorRef cgColor = [UIColor greenColor].CGColor;
CGColorRef cgColor1 = [UIColor redColor].CGColor;
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(id)ctSmallFont, (id)kCTFontAttributeName,
cgColor, (id)kCTForegroundColorAttributeName, nil];
NSDictionary *subattributes = [NSDictionary dictionaryWithObjectsAndKeys:
(id)ctBoldFont, (id)kCTFontAttributeName,
cgColor1, (id)kCTForegroundColorAttributeName, nil];
CFRelease(ctBoldFont);
NSString *subString=#"You must pay 4.00 dollar.";
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:subString attributes:attributes];
[attrStr addAttributes:subattributes range:NSMakeRange(13,4)];
aTextLayer_.string=attrStr;
[self.view.layer addSublayer:aTextLayer_];

If you don't want to use a UIWebView your best options is to use a NSAttributedString.
A naive implementation without caring too much about corner cases and error checking would be something like
NSString * string = #"You must pay 4.00 dollar";
NSString * pattern = #"You must pay (.+) dollar";
NSRegularExpression * regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:NULL];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
NSRange priceRange = [matches[0] rangeAtIndex:1];
NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:string];
[attrString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:priceRange];
Note that I assumed that your patter will always be You must pay (.+) dollar. In case it's different simply adjust the regex in order to retrieve the NSRange of the substring that needs to be stylized.
Then you can use the attributed string as a content of anything accepting a NSAttributedString, for instance UILabel has an attributedText property since iOS 6, therefore you could do something like
yourLabel.attributedText = attrString;

you can add html code to UIWebView
[_webView loadHTMLString:#"<p>You must pay <font color=\"red\">4.00</font> dollar. </p> " baseURL:nil];
try this code
-----------------Alternate Option----------------------------
If this text format is going to be fixed (You must pay XXXX.XXX dollar.) better Create custom component
Create class extend UIView
Add UILable with different font color

Related

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 get a drop shadow on multiline nsstring

I'm trying to get multiline text to draw with a drop shadow without using deprecated APIs. It works fine for a single line. The relevant code looks like this:
-(void)drawRect:(CGRect)rect
{
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
paragraph.lineBreakMode = NSLineBreakByWordWrapping;
paragraph.alignment = NSTextAlignmentCenter;
UIFont *f = [UIFont systemFontOfSize:20.0];
NSMutableDictionary *attributes = [NSMutableDictionary new];
[attributes setValuesForKeysWithDictionary:#{ NSFontAttributeName : f,
NSParagraphStyleAttributeName : paragraph,
NSForegroundColorAttributeName : [UIColor blueColor] }];
NSShadow * shadow = [NSShadow new];
shadow.shadowOffset = CGSizeMake(4,4);
shadow.shadowColor = [UIColor redColor];
[attributes setValue:shadow forKey:NSShadowAttributeName];
rect.origin.y = 100;
[#"test string on one line" drawInRect:rect withAttributes:attributes];
rect.origin.y = 150;
[#"test string spanning more than one line" drawInRect:rect withAttributes:attributes];
}
and the output looks like this:
I have tested this on iPhone 5 (7.1.2), iPhone 6 (8.0), building with xCode 6. I have also tested it on the iPhone 5 when building with xCode 5.
Some more experimentation, and I discovered that the answer is to use an NSAttributedString.
While this does not show a shadow:
NSString *s = #"test string spanning more than one line"
[s drawInRect:rect withAttributes:attributes]
This does:
NSAttributedString *as = [[NSAttributedString alloc] initWithString:s attributes:attributes];
[as drawInRect:rect];
I don't think this is documented anywhere, would love to hear otherwise.

Is is possible to format a specific part of an string within objective-c?

Is it possible to format a section of text in a string within the actual code of xcode to be displayed in a single label? For instance make a specific word bold while leaving the rest normal.
Or do I have to use separate strings with different labels with the specific formatting already determined?
Use attributed text. Example below bolds the word posted By but not the name
NSString *format = NSLocalizedStringFromTable(#"Posted By: %#", #"Details Screen", #"posted by %#");
NSString *text = [NSString stringWithFormat:format, name];
const CGFloat fontSize = 14.0;
UIFont *boldFont = [UIFont fontWithName:#"HelveticaNeue-Bold" size:fontSize];
UIFont *regularFont = [UIFont fontWithName:#"HelveticaNeue" size:fontSize];
UIColor *foregroundColor = [UIColor colorWithWhite:(51.0/255.0) alpha:1.0];
// Create the attributes
NSDictionary *attrs = #{NSFontAttributeName: boldFont,
NSForegroundColorAttributeName: foregroundColor};
NSDictionary *subAttrs = #{NSFontAttributeName: regularFont};
const NSRange range = NSMakeRange(text.length - name.length,name.length); // range of " Posted by: "
// Create the attributed string (text + attributes)
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:text
attributes:attrs];
[attributedText setAttributes:subAttrs range:range];
// Set it in our UILabel and we are done!
[_textLabel setAttributedText:attributedText];

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];
}

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