目标 c - NSFont / NSView 中的字符串对齐



他,当我像这样将文本绘制到我的视图中时:

NSMutableDictionary *textAttrib = [[NSMutableDictionary alloc] init];
[textAttrib setObject:[NSFont fontWithName:@"Helvetica Light" size:15] forKey:NSFontAttributeName];
[textAttrib setObject:[NSColor grayColor] forKey:NSForegroundColorAttributeName];
[mouseString drawAtPoint:textPoint withAttributes:textAttrib];

如何更改文本的对齐方式?我只需要简单的左/右对齐,只能在文本字段中找到任何相关信息。谢谢!

没有与[NSString drawAtPoint:withAttributes:]方法对齐的概念,如果您考虑一下,这是有道理的。 对齐是字符串相对于控件内容(通常是NSTextField(的显示方式的概念。

但是,您可以尝试[NSString drawInRect:withAttributes:]该概念确实存在的地方。 看到这个SO问题。

更新:如果没有@justin给出的(现已删除的(答案,这个问题就不完整,该答案显示了如何在NSAttributedString中设置文本对齐方式。 两个答案都是正确的,但都不完整。

您缺少一个属性:NSParagraphStyleAttributeName,这是一个 NSParagraphStyle 属性。如果创建 NSParagraphStyle 对象,则可以设置此属性:

@property(readonly) NSTextAlignment alignment;  // readwrite for NSMutableParagraphStyle

在您的情况下,您应该将其设置为 NSTextAlignmentLeft 或 NSTextAlignmentRight。

示例

NSMutableParagraphStyle* style=[[NSMutableParagraphStyle alloc]init];
style.alignment= NSTextAlignmentLeft;
[textAttrib setObject: style forKey: NSParagraphStyleAttributeName];

最新更新