Attributed String Alignment?

I’m putting an attributed string into a button, and I’m having trouble with the alignment. It seems that attributed strings don’t pay attention to the button’s setALignment: method either in code, or set in IB. I have this in a part of my code that’s in Objective-C (displayPanel is an NSPanel and displayField is a large square button):

NSFont *displayFont = [NSFont fontWithName:@"Helvetica-BoldOblique" size:18];
    NSString *displayCount = [NSString stringWithFormat:@"%d Clients Found",[uniqueClientArray count]];
    NSDictionary *attribDict = [NSDictionary dictionaryWithObjectsAndKeys:displayFont,NSFontAttributeName,[NSColor whiteColor],NSForegroundColorAttributeName,nil];
    NSAttributedString *attrib = [[NSAttributedString alloc] initWithString:displayCount attributes:attribDict];
    //[displayField setAttributedTitle:attrib];
    //[displayField setAlignment:NSCenterTextAlignment];
    [displayPanel orderFront:self];
    [displayField lockFocus];
    [attrib drawInRect:[displayField bounds]];
    [displayField unlockFocus];
    [displayField display];

The way the code appears above, I don’t see anything --I thought that drawInRect was the way to put attributed strings into a view. If I uncomment the two commented out lines, and comment out the 4 last lines, I do see the string, but it’s not centered.

Ric

Hi,

add a NSParagraphStyle attribute to attribDict, for example


NSMutableParagraphStyle *paragraphStyle;
	
	paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
	[paragraphStyle setAlignment:NSCenterTextAlignment];
	
	NSFont *displayFont = [NSFont fontWithName:@"Helvetica-BoldOblique" size:18];
	NSString *displayCount = [NSString stringWithFormat:@"%d Clients Found",[uniqueClientArray count]];
	NSDictionary *attribDict = [NSDictionary dictionaryWithObjectsAndKeys:displayFont, NSFontAttributeName, [NSColor whiteColor], NSForegroundColorAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil];
	NSAttributedString *attrib = [[NSAttributedString alloc] initWithString:displayCount attributes:attribDict];
	[displayField setAttributedTitle:attrib];
	[attrib release];
	[paragraphStyle release];

Note: as I am an memory management guy, I can’t resist to write the release lines to conform to memory management rules :wink:

Thanks Stefan, that worked great. It’s good to have an Objective-C guru like yourself on the board.

Ric