Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Justified text with UITextView and NSMutableAttributedString

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?

like image 734
Piero Avatar asked May 09 '26 23:05

Piero


1 Answers

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;
like image 73
VoidLess Avatar answered May 12 '26 13:05

VoidLess



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!