Justified text with UITextView and NSMutableAttributedString - ios

I'm trying to put a justified text for a UITextView with NSMutableAttributedString, the NSMutableAttributedString is composed of different NSAttributedString because I need bold and regular font, so I append different NSString, this is my NSMutableAttributedString:
NSAttributedString *one = [[NSAttributedString alloc] initWithString:#"abc"
attributes:boldDict];
NSAttributedString *two = [[NSAttributedString alloc] initWithString:#" def"
attributes:regularDict];
NSAttributedString *three = [[NSAttributedString alloc] initWithString:#" ghi"
attributes:boldDict];
NSMutableAttributedString *string =
[[NSMutableAttributedString alloc] initWithAttributedString:one];
[string appendAttributedString:two];
[string appendAttributedString:three];
I have tried this:
[self.text_view setTextAlignment:NSTextAlignmentJustified]
and this:
NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init];
paragraphStyles.alignment = NSTextAlignmentJustified;
Dictionary *attributes = #{NSParagraphStyleAttributeName: paragraphStyles};
and apply this to NSMutableAttributedString, but neither works. how i can do?

I fixed the same problem by specifying transparent background color for the NSAttributedString.
Looks like a bug in the UILabel code which should render simple NSAttributedString like NSString.
Xamarin.iOS example:
var paragraphStyle = new NSMutableParagraphStyle();
paragraphStyle.Alignment = UITextAlignment.Justified;
var attributedText = new NSAttributedString(simpleString,
paragraphStyle: paragraphStyle,
backgroundColor: Color.Transparent.ToUIColor());
myLabel.AttributedText = attributedText;

Related

UILabel display emojis

I have a UILabel which is displaying emojis incorrectly.
Here is a screenshot from iOS app:
And here is a screenshot from Android app which is displaying the same text with the emoji correctly.
I have tried answers from here but they did not help.
Example string : "تم البيع والله يبارك للمشتري♥️"
Here is the code:
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:comment.body];
UIFont *cellFont = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];
NSDictionary *attributesDictionary;
NSMutableParagraphStyle *paragraphStyle =
[[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 10;
paragraphStyle.alignment = NSTextAlignmentRight;
paragraphStyle.allowsDefaultTighteningForTruncation = true;
attributesDictionary = #{
NSParagraphStyleAttributeName : paragraphStyle,
NSFontAttributeName : cellFont,
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: #(NSUTF8StringEncoding)
};
[str addAttributes:attributesDictionary
range:NSMakeRange(0, str.length)];
cell.commentTextLabel.attributedText = str;
Any help would be appreciated.
Use the emoji's unicode.
in your case, the unicode for the red heart is: U+2764 U+FE0F .
Objective C code :
cell.commentTextLabel.text = #"تم البيع والله يبارك للمشتري \U00002764 \U0000FE0F";
Swift code:
cell.commentTextLabel.text = "تم البيع والله يبارك للمشتري \u{2764} \u{FE0F}"
For more emojis, In Xcode go Edit -> Emoji & Symbols, choose an emoji then right click on it and click Copy Character Info Button. Paste it and you will get for the red heart:
❤️
red heart
Unicode: U+2764 U+FE0F, UTF-8: E2 9D A4 EF B8 8F
I was able to solve this issue by using the following code:
NSData *data = [comment.body dataUsingEncoding:NSUTF16StringEncoding allowLossyConversion:false];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc ] initWithData:data options:#{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
UIFont *cellFont = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];
NSDictionary *attributesDictionary;
NSMutableParagraphStyle *paragraphStyle =
[[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 10;
paragraphStyle.alignment = NSTextAlignmentRight;
attributesDictionary = #{
NSParagraphStyleAttributeName : paragraphStyle,
NSFontAttributeName : cellFont
};
[str addAttributes:attributesDictionary range:NSMakeRange(0, str.length)];
cell.commentTextLabel.attributedText = str;
In here comment.body is the string fetched from server which contains the emoji.
The result was like this:
Thanks to Larme for his help in the comments.

How to just add underline below the second line of text in a Bar Button Item?

This is what I want to achieve:
I'm thinking about having two separate attributed strings and combine them together. Not sure if this is the only way?
UPDATE
The button displays "(null)" if using setAttributedTitle. It can display the right string with no attributes if using setTitle.
Still cannot display in the intended way. Any idea?
// Set current bar button attributes
NSMutableAttributedString *currentBarAttributedString = [[NSMutableAttributedString alloc] init];
[currentBarAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:#"REQUEST\n"
attributes:#{NSUnderlineStyleAttributeName: #(NSUnderlineStyleNone)}]];
[currentBarAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:#"EQUIPMENT"
attributes:#{NSUnderlineStyleAttributeName: #(NSUnderlineStyleSingle)}]];
// Initialize buttons and set titles
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 setAttributedTitle:currentBarAttributedString forState:UIControlStateNormal];
// [button1 setTitle:[currentBarAttributedString string] forState:UIControlStateNormal];
To add border to text or to change color.here is sample code which is used.
use This code in
- (void)viewDidLoad {
[super viewDidLoad];
NSString *strFirst = #"Request Equipment";
NSString *strSecond = #"Active Rentals";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:strFirst
attributes:#{NSUnderlineStyleAttributeName: #(NSUnderlineStyleSingle),
NSForegroundColorAttributeName:[UIColor yellowColor]}]];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:strSecond
attributes:#{NSUnderlineStyleAttributeName: #(NSUnderlineStyleNone),NSForegroundColorAttributeName:[UIColor whiteColor]}]];
//To use attribute string in button
[self.btnAttributeString setAttributedTitle:attributedString forState:UIControlStateNormal];
}
OutPut is
Please check this and let me know any issue.
Just create a NSAttributedString and format it as required
NSString *alertString = #"All heroes do not wear capes.";
NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = NSTextAlignmentLeft;
NSDictionary *attrs = #{
NSParagraphStyleAttributeName: paragraphStyle,
//provide a nsdict here with attributes you want to apply to the whole of the string.
};
NSDictionary *subAttrs = #{
NSParagraphStyleAttributeName: paragraphStyle,
//Here provide attributes for the not underlined part of the string.
};
NSDictionary *subAttrs2 = #{
NSParagraphStyleAttributeName: paragraphStyle,
//Here provide attributes for the underlined part of the string
};
//Set the range of the sub attributes.
const NSRange range = NSMakeRange(0,3);
const NSRange range2 = NSMakeRange(5,4);
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:alertString
attributes:attrs];
[attributedText setAttributes:subAttrs range:range];
[attributedText setAttributes:subAttrs2 range:range2];
Now set this attributed string as your attributed title
class UnderlinedLabel: UILabel {
override var text: String! {
didSet {
let textRange = NSMakeRange(0, count(text))
let textRange = NSMakeRange(0, text.characters.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSUnderlineStyleAttributeName , value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}

How to adjust NSLineBreakByTruncatingTail to a portion of NSAttributedString?

I want to adjust NSLineBreakByTruncatingTail to a portion of NSAttributedString.
For example,
The result is below.
"abcde...LAST"
The 'abcde...' is a NSAttributedString with the properties different with that of 'LAST'.
Actually, I can do if 'abcde...' string object and 'LAST' string object are diffrent.
But, I want to make to same string object.
sample code is below.
NSMutableParagraphStyle *style1 = [[NSMutableParagraphStyle alloc] init];
NSMutableParagraphStyle *style2 = [[NSMutableParagraphStyle alloc] init];
[style2 setLineBreakMode:NSLineBreakByTruncatingTail];
NSMutableAttributedString *attrString1 = [[NSMutableAttributedString alloc] initWithString:#"abcdefghijklm"];
[attrString1 addAttribute:NSForegroundColorAttributeName:[UIColor whiteColor]];
NSMutableAttributedString *attrString2 = [[NSMutableAttributedString alloc] initWithString:#"LAST"];
[attrString2 addAttribute:NSForegroundColorAttributeName:[UIColor blueColor]];
[attrString1 appendAttributedString:attrString2];
Then, I expected like the third line.
But the result is like this.
"abcdefghij..."

Intrinsic content size of UILabel with NSAttributedString and indentation

Why does setting an indent on the paragraph style attribute not have an affect on a UILabel using NSAttributedString?
For example:
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.firstLineHeadIndent = 50;
NSDictionary *attributes = #{
NSForegroundColorAttributeName : [UIColor redColor],
NSParagraphStyleAttributeName : paragraphStyle,
};
NSString *string = #"some string";
self.label.attributedText = [[NSAttributedString alloc] initWithString:string
attributes:attributes];
UILabel with indentation (green background set to see the label size):
UILabel without indentation (green background set to see the label size):

How can I show the text with different fonts in textView in ios?

Hi I am doing one application. In that I need to show text in different fonts. I mean if I show name in one font and I show city name in different font.
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 200, 100)];
textView.text = #"Vijay Apple Dev";
NSString *textViewText = textView.text;
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:textViewText];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Courier" size:20]
range:[textViewText rangeOfString:#"Apple"]];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Verdana" size:20]
range:[textViewText rangeOfString:#"Vijay"]];
textView.attributedText = attributedText;
[self.view addSubview:textView];
Try to do like this one... And customize according to your requirement like font name and font size
NSString *firstName = #"FirstName";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:firstName];
UIFont *font = [UIFont fontWithName:#"Helvetica" size:20];
[attributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, firstName.length)];// Here define your range.
textView.attributedText = attributedString;
//Use attributed String
//Apply properties to both strings
//then merge and set it to textview
NSString *selectedString=#"Hey,";
UIFont *fontSelectedText = [UIFont boldSystemFontOfSize:25];
NSDictionary *dictBoldSelectedText = [NSDictionary dictionaryWithObjectsAndKeys:fontSelectedText, NSFontAttributeName, nil];
NSMutableAttributedString *mutAttrTextViewSelectedString = [[NSMutableAttributedString alloc] initWithString:selectedString];
[mutAttrTextViewSelectedString setAttributes:dictBoldSelectedText range:NSMakeRange(0,selectedString.length)];
[_tTextView setAttributedText:mutAttrTextViewSelectedString];
//Second String
NSString *restOfStrig=#"\nHello";
NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:restOfStrig];
UIFont *fontText = [UIFont boldSystemFontOfSize:16];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
[mutAttrTextViewString setAttributes:dictBoldText range:NSMakeRange(0,restOfStrig.length)];
//Combining both the Attributed String
[mutAttrTextViewSelectedString appendAttributedString:mutAttrTextViewString];
NSMutableAttributedString * finalAttributedStr=[[NSMutableAttributedString alloc] initWithAttributedString:mutAttrTextViewSelectedString];
//setting it to the textView
[_tTextView setAttributedText:finalAttributedStr];
Use NSAttributedString
An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string. The cluster’s two public classes, NSAttributedString and NSMutableAttributedString, declare the programmatic interface for read-only attributed strings and modifiable attributed strings, respectively.
NSAttributedString
When you create your attributed string, then just set it to your textView:
self.textView.attributedText = myAttributedString;

Resources