我用AppKit创建了一个NSMenu里面的每有些NSMenuItem的image属性分配了一个NSImage然而有的却没有。如何让他们的文字内容对齐而不是靠左对齐
您可以使用NSMenuItem的setAttributedTitle方法,将文字内容设置为富文本格式,并使用NSTextAttachment来添加图片。这样可以实现自定义对齐方式。
例如,以下代码将一个图片和文字内容居中对齐:
NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:@"Menu Item" action:nil keyEquivalent:@""];
NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:@"Menu Item"];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [NSImage imageNamed:@"image"];
attachment.bounds = CGRectMake(0, 0, 16, 16);
NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
[attributedTitle appendAttributedString:attachmentString];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentCenter];
[attributedTitle addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedTitle.length)];
[menuItem setAttributedTitle:attributedTitle];
在上面的代码中,我们首先创建了一个NSMenuItem对象,并设置了其标题为“Menu Item”。然后,我们创建了一个NSMutableAttributedString对象,将其设置为“Menu Item”的文本内容,并使用NSTextAttachment来添加了一个图片。接下来,我们创建了一个NSMutableParagraphStyle对象,并将其对齐方式设置为居中。最后,我们将NSMutableAttributedString对象设置为NSMenuItem的富文本标题
原文地址: https://www.cveoy.top/t/topic/hjO8 著作权归作者所有。请勿转载和采集!