【发布时间】:2015-01-10 11:39:21
【问题描述】:
我想知道如何在 swift 中将标题颜色更改为 NSButton,我在 Objective-c 中看到了很多示例,但我认为在 swift 中实现是不同的,谁能给我一个示例?
【问题讨论】:
标签: macos swift xcode6 nsbutton
我想知道如何在 swift 中将标题颜色更改为 NSButton,我在 Objective-c 中看到了很多示例,但我认为在 swift 中实现是不同的,谁能给我一个示例?
【问题讨论】:
标签: macos swift xcode6 nsbutton
在viewDidLoad 或其他地方试试这个。
在 Swift 3 中:
let pstyle = NSMutableParagraphStyle()
pstyle.alignment = .center
button.attributedTitle = NSAttributedString(string: "Title", attributes: [ NSForegroundColorAttributeName : NSColor.red, NSParagraphStyleAttributeName : pstyle ])
【讨论】:
.CenterTextAlignment 更改为 .Center
let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center button.attributedTitle = NSAttributedString(string: "Title", attributes: [NSForegroundColorAttributeName : NSColor.red, NSParagraphStyleAttributeName : paragraphStyle])
斯威夫特 4
我已将此作为附加答案添加,因为它仅更改请求的属性而不会覆盖或添加其他属性。
if let mutableAttributedTitle = button.attributedTitle.mutableCopy() as? NSMutableAttributedString {
mutableAttributedTitle.addAttribute(.foregroundColor, value: NSColor.white, range: NSRange(location: 0, length: mutableAttributedTitle.length))
button.attributedTitle = mutableAttributedTitle
}
【讨论】:
在 Swift4 中
button.attributedTitle = NSMutableAttributedString(string: "Hello World", attributes: [NSAttributedStringKey.foregroundColor: NSColor.white, NSAttributedStringKey.paragraphStyle: style, NSAttributedStringKey.font: NSFont.systemFont(ofSize: 18)])
【讨论】: