Convert NSString to HTML and set HTML text into UILabel [duplicate] - objective-c

This question already has answers here:
How to create a UILabel or UITextView with bold and normal text in it?
(5 answers)
Closed 9 years ago.
Is it possible to convert a NSString to html and set as a label?
The code below shows the NSString I want to set finalPrice as bold text and finalStr&shipping string as normal text
NSString *myText = [NSString
stringWithFormat:
#"%#\nFinal price including $%.2f Shipping and all discount: <b>$%.2f</b>",
finalStr,shipping,finalPrice];
lbl.text = myText;
I want to set multiple color and multiple text type into same dyanamic label.

use following label for bold effects. Or you can get code from that class.
DAAttributedStringUtils
and also see this
Different Label
Edit
NSString *myText = [NSString stringWithFormat:#"%#\nFinal price including $%.2f Shipping and all discount: %%B$%.2f%%b",finalStr,shipping,finalPrice];
DAAttributedLabel* lbl = [[DAAttributedLabel alloc] initWithFrame:CGRectMake(30.0f, 30.0f, 260.0f, 24.0f)];
lbl.backgroundColor = [UIColor colorWithRed:0.9f green:0.9f blue:1.0f alpha:1.0f];
lbl.text = (id)[formatter formatString:myText];
[self.view addSubview:lbl];

Try using NSAttributedString
There are already several questions around this here like
How do you use NSAttributedString?
NSString * textString = #"Hello Bold";
NSInteger _stringLength = [textString length];
NSMutableAttributedString * attString = [[NSMutableAttributedString alloc] initWithString:textString];
[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica" size:14.0f]; range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica-Bold" size:14.0f]; range:NSMakeRange(6, 4)];
myLabel.attributedText = attString;
(code not tested)
Edit:
label.attributedText is only available for iOS 6.0+

FYI, the answer above suggesting the use of DAAttributedStringUtils and DAAttributedLabel didn't mention that these are convenience classes for the use of NSAttributedString. They make formatting NSAttributedString instances a little easier. As an example, here's how to do the same formatting described about by HAS using DAAttributedStringUtils:
float finalPrice = 34.99, shipping = 4.99;
// Setup the formatter
DAAttributedStringFormatter* formatter = [[DAAttributedStringFormatter alloc] init];
formatter.defaultFontFamily = #"Georgia";
formatter.defaultFontSize = 12.0f;
formatter.colors = #[ [UIColor blackColor], [UIColor redColor] ];
NSAttributedString* attrStr = [formatter formatString:#"%0C%0FRed Courier Text %1C%1FBlue Arial Text %0CRed Arial Text"];
// setup base strings
NSString *finalStr = #"Some Text. ";
NSString *shippingAttributed = [NSString stringWithFormat:#"%%B%%1C$%.2f%%b%%c", shipping];
NSString *middleText0 = #"Final price including ";
NSString *middleText1 = #" Shipping and all discount: ";
NSString *finalPriceAttributed = [NSString stringWithFormat:#"%%B%%1C$%.2f%%b%%c", finalPrice];
// Format the strings
self.label.attributedText = [formatter formatString:[NSString stringWithFormat:#"%#%#%%B%%1C%#%%b%%c%#%%B%%1C%#", finalStr, shippingAttributed, middleText0, middleText1, finalPriceAttributed];
Somewhat less code, and I think easier to understand. FYI, the formatter string in the last line contains codes that are used to modify the format of portions of the string. Those codes use double percents (

Related

Objective C label line spacing?

Is there a way to set the distance of two lines within a UILabel?
I tried to do it within Interface Builder but without success.
The code you want will be something like this:
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:#"Sample text"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:24];
[attrString addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, strLength)];
uiLabel.attributedText = attrString;
You can use NSAttributedString to add spacing between two lines within a UILabel:
NSString *labelText = #"My String";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:20];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
cell.label.attributedText = attributedString ;
OR
If you are using storyboard then you can control line spacing in the storyboard by selecting text type is attributed and add spacing value:
Since iOS 6, Apple added NSAttributedString to UIKit, making it possible to use NSParagraphStyle to change the line spacing.
Alternatively, you can do this via Storyboards using Attributed Text and then clicking the ... symbol. See link below for screenshot.
https://i.stack.imgur.com/aiNfR.png

changing colour of a part of string objective c [duplicate]

This question already has answers here:
Are there any analogues of [NSString stringWithFormat:] for NSAttributedString
(4 answers)
Closed 6 years ago.
I have a string like this
NSString * string = [[NSString alloc]initwithformat: #"The current balance left is %# out of %#",leftAmount,totalAmount];
How can i change the colour of string recieved as %# without knowing the range of the recieved string.
Do something like this,
NSString *leftAmount = #"1000";
NSString *totalAmount = #"2000";
UIColor *color = [UIColor redColor];
NSDictionary *attrs = #{ NSForegroundColorAttributeName : color };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:leftAmount attributes:attrs];
NSAttributedString *attrStr1 = [[NSAttributedString alloc] initWithString:totalAmount attributes:attrs];
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:#"The current balance left is "];
[string appendAttributedString:attrStr];
NSMutableAttributedString * string1 = [[NSMutableAttributedString alloc] initWithString:#" out of "];
[string1 appendAttributedString:attrStr1];
[string appendAttributedString:string1];
NSLog(#"Your Full String - %#", string);
Hope this will help you.
do something like this,
NSString *leftAmount,*totalAmount;
leftAmount = #"1000";
totalAmount = #"2000";
NSString * string = [NSString stringWithFormat:#"The current balance left is %# out of %#",leftAmount,totalAmount];
NSDictionary *attribs = #{
NSForegroundColorAttributeName: [UIColor blueColor],
NSFontAttributeName: [UIFont systemFontOfSize:12]
};
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:string
attributes:attribs];
UIColor *grayColor = [UIColor colorWithRed:186.0f/255.0f green:186.0f/255.0f blue:186.0f/255.0f alpha:1];
NSRange leftAmountTextRange = [string rangeOfString:leftAmount];
[attributedText setAttributes:#{NSForegroundColorAttributeName:grayColor}
range:leftAmountTextRange];
It'll also calculate the dynamic data value range.
I hope it will helps you,
Thanks.

Custom NSFormatter in Objective C

I am trying to write my own custom formatter in Objective C by subclassing NSNumberFormatter. Specifically what I'd like to do is make a number turn red if it is above or below certain values. The apple documentation says
For example, if you want negative financial amounts to appear in red, you have this method return a string with an attribute of red text. In attributedStringForObjectValue:withDefaultAttributes: get the non-attributed string by invoking stringForObjectValue: and then apply the proper attributes to that string.
Based on this advice I implemented the following code
- (NSAttributedString*) attributedStringForObjectValue: (id)anObject withDefaultAttributes: (NSDictionary*)attr;
{
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:[self stringForObjectValue:anObject]];
if ([[attrString string] floatValue] < -20.0f) {
[attrString addAttribute:#"NSForegroundColorAttributeName" value:[NSColor redColor] range:NSMakeRange(0, 10)];
return attrString;
} else return attrString;
}
But when I test this all it does is freeze my application. Any advice would be appreciated. Thanks.
I believe this has something to do with your NSRange that you create. I believe your length (10 in your example) is out of bounds. Try getting the length of the string that you use to initialize your NSMutableAttributedString.
For example:
- (NSAttributedString*) attributedStringForObjectValue: (id)anObject withDefaultAttributes: (NSDictionary*)attr;
{
NSString *string = [self stringForObjectValue:anObject];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSInteger stringLength = [string length];
if ([[attrString string] floatValue] < -20.0f)
{
[attrString addAttribute:#"NSForegroundColorAttributeName" value:[NSColor redColor] range:NSMakeRange(0, stringLength)];
}
return attrString;
}
Here is how I was finally able to implement this. To make it more visible when a number is negative, I decided to make the background of the text red with white text. The following code does work in a NSTextField cell. I'm not sure why the code in my question (and the answer) does not work, addAttribute should work.
- (NSAttributedString *)attributedStringForObjectValue:(id)anObject withDefaultAttributes: (NSDictionary *)attributes{
NSString *string = [self stringForObjectValue:anObject];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSInteger stringLength = [string length];
if ([[attrString string] floatValue] < 0)
{
NSDictionary *firstAttributes = #{NSForegroundColorAttributeName: [NSColor whiteColor],
NSBackgroundColorAttributeName: [NSColor blueColor]};
[attrString setAttributes:firstAttributes range:NSMakeRange(0, stringLength)];
}
return attrString;
}

How to make subscripts and superscripts using NSAttributedString?

I need to make subscripts for chemistry formulas (H2O, Na^2+, etc)?
Is this possible to do with NSAttributedString, or is there an alternative/easier way to make subscripts?
Here's what I did in iOS 6. First add the CoreText, and QuartzCore frameworks. Then import:
#import <QuartzCore/QuartzCore.h>
#import <CoreText/CTStringAttributes.h>
#import <CoreText/CoreText.h>
I made a small function that inputs a plain NSString and exports a NSMutableAttributedString with the last character in superscript. This can be modified to allow setting superscript or subscript, change kCTSuperscriptAttributeName value to -1. Also you could add a variable to specify where to put the superscript in the string. Right now it just assumes the end of the string.
- (NSMutableAttributedString *)plainStringToAttributedUnits:(NSString *)string;
{
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string];
UIFont *font = [UIFont systemFontOfSize:10.0f];
UIFont *smallFont = [UIFont systemFontOfSize:9.0f];
[attString beginEditing];
[attString addAttribute:NSFontAttributeName value:(font) range:NSMakeRange(0, string.length - 2)];
[attString addAttribute:NSFontAttributeName value:(smallFont) range:NSMakeRange(string.length - 1, 1)];
[attString addAttribute:(NSString*)kCTSuperscriptAttributeName value:#"1" range:NSMakeRange(string.length - 1, 1)];
[attString addAttribute:(NSString*)kCTForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, string.length - 1)];
[attString endEditing];
return attString;
}
Now when I want to use it I can do the following to put it in a UITextField:
NSString *qlwUnitsPlainText = #"m3";
self.quantityLoadWeightUnits_textField.attributedText = [self plainStringToAttributedUnits:qlwUnitsPlainText];
I hope this helps somebody else, there's not many examples out there!
This is possible to do with NSAttributedString. The attribute constant you're looking for depends on your platform. For Mac OS X it is NSSuperscriptAttributeName and on iOS it is kCTSuperscriptAttributeName. Pass in a negative value for subscript.
The only caveat is that UILabel on iOS can't draw NSAttributedStrings (yet, fingers crossed for iOS 6). You would need to draw the text using Core Text or find some third party replacement for UILabel that can draw an NSAttributedString.
On iOS, I had missed the kCTSuperscriptAttributeName constant but had good results with font size and "baseline". It gives you a little more control too for less obedient fonts:
+ (NSAttributedString *)attributedStringForText:(NSString *)normalText andSuperscript:(NSString *)superscriptText textSize:(CGFloat)textSize
{
UIFont *normalFont = [Styles mainFontWithSize:textSize];
UIFont *superFont = [Styles mainFontWithSize:textSize / 2];
NSMutableAttributedString *finalStr = [[NSMutableAttributedString alloc] initWithString:normalText attributes:#{NSFontAttributeName: normalFont}];
NSAttributedString *superStr = [[NSAttributedString alloc] initWithString:superscriptText attributes:#{NSFontAttributeName: superFont, NSBaselineOffsetAttributeName:#(textSize/2)}];
[finalStr appendAttributedString:superStr];
return finalStr;
}
For SubScript use value for kCTSuperscriptAttributeName as #-1.
As per the document
#discussion Value must be a CFNumberRef. Default is int value 0. If
supported
by the specified font, a value of 1 enables superscripting and a
value of -1 enables subscripting.
extern const CFStringRef kCTSuperscriptAttributeName
CT_AVAILABLE(10_5, 3_2);
Example- [lblHeader setText:#“Headers [Alpha1 – text”];
NSMutableAttributedString *headerSubscript = [[NSMutableAttributedString alloc]initWithAttributedString: lblHeader.attributedText];
[headerSubscript addAttribute:(NSString *)kCTSuperscriptAttributeName value:#-1 range:NSMakeRange(14,1)];
[lblHeader setAttributedText:headerSubscript];
you can also do the following if you want to make it a litle cleaner
NSDictionary *attr = #{ NSFontAttributeName: smallfont,
(NSString*)kCTSuperscriptAttributeName: #1 }
NSRange fabricWeightRange = NSMakeRange(fabricWeight.location + 2, 1);
[subKeyString setAttributes:attr range:fabricWeightRange];

Any way to bold part of a NSString?

Is there any way to bold only part of a string?
For example:
Approximate Distance: 120m away
Thanks!
What you could do is use an NSAttributedString.
NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = ...;
NSRange boldedRange = NSMakeRange(22, 4);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
[attrString beginEditing];
[attrString addAttribute:kCTFontAttributeName
value:boldFontName
range:boldedRange];
[attrString endEditing];
//draw attrString here...
Take a look at this handy dandy guide to drawing NSAttributedString objects with Core Text.
As Jacob mentioned, you probably want to use an NSAttributedString or an NSMutableAttributedString. The following is one example of how you might do this.
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:#"Approximate Distance: 120m away"];
NSRange selectedRange = NSMakeRange(22, 4); // 4 characters, starting at index 22
[string beginEditing];
[string addAttribute:NSFontAttributeName
value:[NSFont fontWithName:#"Helvetica-Bold" size:12.0]
range:selectedRange];
[string endEditing];
If you do not want to bother with fonts (as not every variation of font contains "Bold"), here is another way to do this. Please be aware, this is currently only available on OS X...:
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:"Approximate Distance: 120m away"];
[attrString beginEditing];
[attrString applyFontTraits:NSBoldFontMask
range:NSMakeRange(22, 4)];
[attrString endEditing];
The code above gave me crash when I created UILabel with this attributedString.
I used this code and it worked:
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSRange boldedRange = NSMakeRange(0, 1);
UIFont *fontText = [UIFont systemFontOfSize:12]; //[UIFont fontWithName:#"Lato-Bold" size:12];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
[attrString setAttributes:dictBoldText range:boldedRange];
Swift
Also includes getting the range of the string you want to embolden dynamically
let nameString = "Magoo"
let string = "Hello my name is \(nameString)"
let attributes = [NSFontAttributeName:UIFont.systemFontOfSize(14.0),NSForegroundColorAttributeName: UIColor.black]
let boldAttribute = [NSFontAttributeName:UIFont.boldSystemFontOfSize(14.0)]
let attributedString = NSMutableAttributedString(string: string, attributes: attributes)
let nsString = NSString(string: string)
let range = nsString.rangeOfString(nameString)
if range.length > 0 { attributedString.setAttributes(boldAttribute, range: range) }
someLabel.attributedText = attributedString
To bold a string without hardcoding its font, you can use the StrokeWidth attribute with a negative value:
let s = NSMutableAttributedString(string: "Approximate Distance: 120m away")
s.addAttribute(NSStrokeWidthAttributeName, value: NSNumber(value: -3.0), range: NSRange(22..<26))
An NSString is just a data container. It doesn't contain any details about presentation concerns.
It sounds like what you probably want to do is bold part of the UILabel that is being used to display your string. Which I don't think you can do. But you could always break the UI down into three labels, one for "Approximate Distance:", one for "120 m", and one for "away". Place them in-line with each other and you should get the desired effect.
Another option might be to use a UIWebView and a little bit of markup to display your string with embedded formatting information, as discussed here:
http://iphoneincubator.com/blog/windows-views/display-rich-text-using-a-uiwebview
In Xamarin ios you can bold part of a NSString this way:
public static NSMutableAttributedString BoldRangeOfString (string str, float fontSize, int startRange, int lengthRange)
{
var firstAttributes = new UIStringAttributes {
Font = UIFont.BoldSystemFontOfSize(fontSize)
};
NSMutableAttributedString boldString = new NSMutableAttributedString (str);
boldString.SetAttributes (firstAttributes.Dictionary, new NSRange (startRange, lengthRange));
return boldString;
}
and call this method:
myLabel = new UILabel ();
...
myLabel.AttributedText = BoldRangeOfString("my text", fontSize, startRange, lengthRange);
I coupled #Jacob Relkin and #Andrew Marin answers, otherwise, I got the crashes. Here is the answer for iOS9:
UIFont *boldFont = [UIFont boldSystemFontOfSize:12];
NSString *yourString = #"Approximate Distance: 120m away";
NSRange boldedRange = NSMakeRange(22, 4);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName
value:boldFont
range:boldedRange];
[attrString endEditing];
I took a look at the official documentation: 1 and 2.
Shorter way using Swift5+
let labelNotes = UILabel() //or UITextView(), etc...
let attributedNotes = NSMutableAttributedString(string: "Bold: some stuff not bold")
attributedNotes.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 14), range: NSRange(location: 0, length: 5))
labelNotes.attributedText = attributedNotes
If you don't want to hardcode the font or/and the size try this code for bolding full strings:
NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithString:mainString];
[myString beginEditing];
[myString addAttribute:NSStrokeWidthAttributeName
value:[[NSNumber alloc] initWithInt: -3.f]
range:NSMakeRange(0, [mainString length])];
[myString endEditing];