如何修改NSButton标题颜色而不更改标题文本?
为什么你之前的代码报错
NSAttributedString没有仅通过attributes参数初始化的构造方法,必须传入字符串内容,所以不能直接移除string: "foo"参数,得用按钮原有的标题文本替代固定字符串。
单个按钮的修改方案
根据按钮原有标题类型,分两种处理方式:
情况1:按钮是普通文本标题
直接基于原标题文本生成带颜色的富文本:
guard let originalText = button.currentTitle else { return } // 按需配置段落样式,若不需要可省略 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = button.alignment // 保留原对齐方式 let coloredAttributedTitle = NSAttributedString( string: originalText, attributes: [ .foregroundColor: NSColor.black, .paragraphStyle: paragraphStyle ] ) button.attributedTitle = coloredAttributedTitle
情况2:按钮已有富文本标题
保留原有富文本属性,仅修改颜色:
let mutableAttributedTitle = NSMutableAttributedString(attributedString: button.attributedTitle) // 给整个文本范围设置颜色 let fullRange = NSRange(location: 0, length: mutableAttributedTitle.length) mutableAttributedTitle.addAttribute( .foregroundColor, value: NSColor.black, range: fullRange ) button.attributedTitle = mutableAttributedTitle
遍历视图控制器所有NSButton的方法
写一个递归函数,遍历视图层级里的所有按钮并修改颜色:
func updateAllButtonColors(in view: NSView) { for subview in view.subviews { if let button = subview as? NSButton { // 这里用上述任意一种修改方式,示例用保留原富文本的方案 let mutableAttrTitle = NSMutableAttributedString(attributedString: button.attributedTitle) mutableAttrTitle.addAttribute( .foregroundColor, value: NSColor.black, range: NSRange(location: 0, length: mutableAttrTitle.length) ) button.attributedTitle = mutableAttrTitle } // 递归处理子视图的子视图 updateAllButtonColors(in: subview) } } // 在视图控制器的viewDidLoad中调用 override func viewDidLoad() { super.viewDidLoad() updateAllButtonColors(in: self.view) }
内容的提问来源于stack exchange,提问作者Abdo Assem11
相关产品推荐
相关产品推荐

