Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attributed Text Center Alignment

I have tried everything but cannot seem to center this text. Can someone please tell me where the error is.

NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new; paragraphStyle.alignment = NSTextAlignmentCenter; label.attributedText = [[NSAttributedString alloc] initWithString:cell.EventTitle.text attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle,NSBaselineOffsetAttributeName : @0,NSFontAttributeName : [UIFont fontWithName:@"BrandonGrotesque-Black" size:34]}]; 
like image 798
user3255746 Avatar asked Mar 14 '15 05:03

user3255746


People also ask

How to give align center in HTML?

The attribute is used with the HTML <p> tag, with the CSS property text-align for the center, left and right alignment. HTML5 do not support the align attribute of the <p> tag, so the CSS style is used to set text alignment.

What is an attributed string?

Overview. Attributed strings are character strings that have attributes for individual characters or ranges of characters. Attributes provide traits like visual styles for display, accessibility for guided access, and hyperlink data for linking between data sources.


2 Answers

In Swift 5

let paragraph = NSMutableParagraphStyle() paragraph.alignment = .center textView.attributedText = NSAttributedString(string: "String",                                                      attributes: [.paragraphStyle: paragraph]) 

In Swift-4

let paragraph = NSMutableParagraphStyle() paragraph.alignment = .center  let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.paragraphStyle: paragraph] let attrString = NSAttributedString(string:"string", attributes: attributes) textView.attributedText =  attrString 

In Swift-3

let paragraph = NSMutableParagraphStyle() paragraph.alignment = .center  let attributes: [String : Any] = [NSParagraphStyleAttributeName: paragraph] let attrString = NSAttributedString(string:"string", attributes: attributes) textView.attributedText =  attrString 
like image 93
Shrawan Avatar answered Oct 08 '22 11:10

Shrawan


You can set the center alignment using this. Remember to set range.

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setAlignment:NSTextAlignmentCenter];  NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string]; [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])]; 
like image 22
user3575114 Avatar answered Oct 08 '22 12:10

user3575114