[ios] NSAttributedString add text alignment

How can I add text alignment attribute to an NSAttributedString to center the text?

Edit: Am I doing anything wrong? It doesn't seem to change the alignment.

CTParagraphStyleSetting setting;
setting.spec = kCTParagraphStyleSpecifierAlignment;
setting.valueSize = kCTCenterTextAlignment;

CTParagraphStyleSetting settings[1] = {
    {kCTParagraphStyleSpecifierAlignment, sizeof(CGFloat), &setting},           
};

CTParagraphStyleRef paragraph = CTParagraphStyleCreate(settings, sizeof(setting));

NSMutableAttributedString *mutableAttributed = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedString];
[mutableAttributed addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:(NSObject*)paragraph ,(NSString*) kCTParagraphStyleAttributeName, nil] range:_selectedRange];

This question is related to ios objective-c nsattributedstring core-text

The answer is


Swift 4.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center

let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered", 
    attributes: [.font: titleFont,    
    .foregroundColor: UIColor.red, 
    .paragraphStyle: titleParagraphStyle])

Swift 3.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center

let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered", 
    attributes: [NSFontAttributeName:titleFont,    
    NSForegroundColorAttributeName:UIColor.red, 
    NSParagraphStyleAttributeName: titleParagraphStyle])

(original answer below)

Swift 2.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .Center

let titleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
let title = NSMutableAttributedString(string: "You Are Registered",
    attributes:[NSFontAttributeName:titleFont,   
    NSForegroundColorAttributeName:UIColor.redColor(), 
    NSParagraphStyleAttributeName: titleParagraphStyle])

I was searching for the same issue and was able to center align the text in a NSAttributedString this way:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];

NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
[attribString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];

Xamarin.iOS

NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle();
paragraphStyle.HyphenationFactor = 1.0f;
var hyphenAttribute = new UIStringAttributes();
hyphenAttribute.ParagraphStyle = paragraphStyle;
var attributedString = new NSAttributedString(str: name, attributes: hyphenAttribute);

[averagRatioArray addObject:[NSString stringWithFormat:@"When you respond Yes to %@ the average response to    %@ was %0.02f",QString1,QString2,M1]];
[averagRatioArray addObject:[NSString stringWithFormat:@"When you respond No  to %@ the average response to    %@ was %0.02f",QString1,QString2,M0]];

UIFont *font2 = [UIFont fontWithName:@"Helvetica-Bold" size:15];
UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:12];

NSMutableAttributedString *str=[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"When you respond Yes to %@ the average response to %@ was",QString1,QString2]];
[str addAttribute:NSFontAttributeName value:font range:NSMakeRange(0,[@"When you respond Yes to " length])];
[str addAttribute:NSFontAttributeName value:font2 range:NSMakeRange([@"When you respond Yes to " length],[QString1 length])];
[str addAttribute:NSFontAttributeName value:font range:NSMakeRange([QString1 length],[@" the average response to " length])];
[str addAttribute:NSFontAttributeName value:font2 range:NSMakeRange([@" the average response to " length],[QString2 length])];
[str addAttribute:NSFontAttributeName value:font range:NSMakeRange([QString2 length] ,[@" was" length])];
// [str addAttribute:NSFontAttributeName value:font2 range:NSMakeRange(49+[QString1 length]+[QString2 length] ,8)];
[averagRatioArray addObject:[NSString stringWithFormat:@"%@",str]];

Swift 4 answer:

// Define paragraph style - you got to pass it along to NSAttributedString constructor
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center

// Define attributed string attributes
let attributes = [NSAttributedStringKey.paragraphStyle: paragraphStyle]

let attributedString = NSAttributedString(string:"Test", attributes: attributes)

In swift 4:

    let paraStyle = NSMutableParagraphStyle.init()
    paraStyle.alignment = .left

    let str = "Test Message"
    let attribute = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 12)]

    let attrMessage = NSMutableAttributedString(string: str, attributes: attribute)


    attrMessage.addAttribute(kCTParagraphStyleAttributeName as NSAttributedStringKey, value: paraStyle, range: NSMakeRange(0, str.count))

 NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
 paragraphStyle.alignment                = NSTextAlignmentCenter;

 NSAttributedString *attributedString   = 
[NSAttributedString.alloc initWithString:@"someText" 
                              attributes:
         @{NSParagraphStyleAttributeName:paragraphStyle}];

Swift 4.2

let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.center

    let attributedString = NSAttributedString(string: "someText", attributes: [NSAttributedString.Key.paragraphStyle : paragraphStyle])

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to nsattributedstring

Swift: Display HTML data in a label or textView How to underline a UILabel in swift? How do I make an attributed string using Swift? How can I make a clickable link in an NSAttributedString? Change string color with NSAttributedString? boundingRectWithSize for NSAttributedString returning wrong size NSAttributedString add text alignment Convert HTML to NSAttributedString in iOS Bold & Non-Bold Text In A Single UILabel? How do you use NSAttributedString?

Examples related to core-text

NSAttributedString add text alignment Convert HTML to NSAttributedString in iOS