我正在开发我的第一个 Swift 项目(万岁),这是一个适用于 Mac OS 的应用程序。我现在想做的是创建一些带有白色文本颜色和自定义字体的按钮。因为我需要该按钮上的新属性来保存一些数据,所以我创建了 NSButton
的子类。
现在,我知道我可以像这样设置按钮的字体:
super.font = NSFont(name: "NB-International-Pro", size: 40)
这就像一个魅力。之后我尝试通过这样做来更改文本的颜色:
let pstyle = NSMutableParagraphStyle()
pstyle.alignment = .center
super.attributedTitle = NSAttributedString(string: (device?.name)!, attributes: [ NSForegroundColorAttributeName : NSColor.white, NSParagraphStyleAttributeName : pstyle ])
这确实有效,并且确实改变了文本的颜色,但是,现在字体和字体大小恢复为默认值。有没有办法同时执行这两项操作?
谢谢。
最佳答案
不要先设置字体,而是在使用 NSFontAttributeName
和 NSFontSizeAttribute
创建 NSAttributedString
时在属性中包含字体名称和大小键:
attributedTitle = NSAttributedString(string: (device?.name)!, attributes: [ NSForegroundColorAttributeName : NSColor.white, NSParagraphStyleAttributeName : pstyle, NSFontAttributeName: "NB-International-Pro", NSFontSizeAttribute: 40])
除此之外,您可能还可以对代码架构进行一些改进。子类化 NSButton
并不只是为了更改文本样式(可以在 .xib 或 View Controller 中完成)。
关于swift - 更改 NSButton 的字体大小不会改变任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43537903/