设计稿常常要求文本水平居中,如果文本是单行的NSString,则可以用NSTextField的alignment属性实现,代码如下:
self.manage = [[NSTextField alloc] initWithFrame:NSMakeRect(0, y, panelWidth, height)]; // Focus on x=0 and width=panelWidth
self.manage.stringValue = @"管理备份文件";
self.manage.alignment = NSCenterTextAlignment;
[self.panel addSubview:self.manage];
效果如下:

如果文本是单行的NSAttributedString,如下的“其中1个文件无法收藏”,就不能像上面一样了

实现代码如下:
self.desc = [[NSTextField alloc] initWithFrame:NSMakeRect(0, y, panelWidth, height)]; [attributedStr setAlignment:NSCenterTextAlignment range:NSMakeRange(0, attributedStr.length)]; // Focus on this line
self.desc.attributedStringValue = attributedStr;
[self.panel addSubView: self.desc];