Wie*_*nke 3 cocoa nstextfield nsattributedstring
我有一个面板笔尖,其中一个文本字段的出口,在笔尖中设置为居中对齐.当我显示面板时,我希望这个文本字段是粗体.由于NSTextField是NSControl的子类,因此它可以使用setAttributedStringValue方法并获取属性字符串.所以我加入了这样的粗体字体:
NSFont *fontBolded = [NSFont fontWithName:@"Baskerville Bold" size:12.0f];
NSDictionary *dictBoldAttr = [NSDictionary dictionaryWithObject:fontBolded forKey:NSFontAttributeName];
NSString *sHelloUser = NSLocalizedString(@"Hello User", @"Hello User");
NSAttributedString *attrsHelloUser = [[NSAttributedString alloc] initWithString: sHelloUser attributes:dictBoldAttr];
[self.fooController.tfPanelCenteredField setAttributedStringValue:attrsHelloUser];
[attrsHelloUser release];
Run Code Online (Sandbox Code Playgroud)
粗体显示OK,但现在该字段左对齐.
我尝试添加setAlignment,但它没有效果:
[self.fooController.tfPanelCenteredField setAlignment:NSCenterTextAlignment];
Run Code Online (Sandbox Code Playgroud)
所以我尝试将一个居中的parapraph样式添加到属性字符串的属性中:
NSFont *fontBolded = [NSFont fontWithName:@"Baskerville Bold" size:12.0f];
NSMutableParagraphStyle *paragStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragStyle setAlignment:NSCenterTextAlignment];
NSDictionary *dictBoldAttr = [NSDictionary dictionaryWithObjectsAndKeys:paragStyle, NSParagraphStyleAttributeName, fontBolded, NSFontNameAttribute, nil];
NSString *sHelloUser = NSLocalizedString(@"Hello User", @"Hello User");
NSAttributedString *attrsHelloUser = [[NSAttributedString alloc] initWithString: sHelloUser attributes:dictBoldAttr];
[self.fooController.tfPanelCenteredField setAttributedStringValue:attrsHelloUser];
[attrsHelloUser release];
[paragStyle release];
Run Code Online (Sandbox Code Playgroud)
现在文本字段再次居中,但粗体消失了.就好像属性字符串可以接受一个且只有一个属性设置.我错过了一些简单的事吗?
您的代码中有拼写错误.NSFontNameAttribute应该是NSFontAttributeName.
所以你的属性字典是:
NSFont *fontBolded = [NSFont fontWithName:@"Baskerville Bold" size:12.0f];
NSMutableParagraphStyle *paragStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragStyle setAlignment:NSCenterTextAlignment];
NSDictionary *dictBoldAttr = [NSDictionary dictionaryWithObjectsAndKeys:
fontBolded, NSFontAttributeName,
paragStyle, NSParagraphStyleAttributeName,
nil];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3778 次 |
| 最近记录: |