【问题标题】:Change Font For NSButton With Inspectable/Designable Property使用 Inspectable/Designable 属性更改 NSButton 的字体
【发布时间】:2020-05-01 23:43:12
【问题描述】:

不知道该怎么做。我发现了一个自定义 NSButton 类的代码块,它可以检查字体大小和颜色的属性,仅此而已。有没有办法将我的 Mac 上的字体集添加到我可以为这个类更改的属性中,或者获取我在其他可设置属性中设置的字体,比如标题?这是课程:

import Cocoa

class TextButton: NSButton {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }

    @IBInspectable open var textColor: NSColor = NSColor.black
    @IBInspectable open var textSize: CGFloat = 10


    public override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }

    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func awakeFromNib() {
        let titleParagraphStyle = NSMutableParagraphStyle()
        titleParagraphStyle.alignment = alignment

        let attributes: [NSAttributedString.Key : Any] = [.foregroundColor: textColor, .font: NSFont.boldSystemFont(ofSize: textSize), .paragraphStyle: titleParagraphStyle]
        self.attributedTitle = NSMutableAttributedString(string: self.title, attributes: attributes)
    }

}

【问题讨论】:

    标签: swift xcode fonts nsbutton


    【解决方案1】:

    我想我找到了解决办法。似乎工作。我正在寻找一种方法来制作一个未倾斜的按钮,以便在单击时正确突出显示,但 IB 不会让你这样做。圆形按钮是一种您可以选择的样式,但不鼓励使用,因此我必须进一步寻找解决方案。

    @IBDesignable
    class TextButton: NSButton
    {
        @IBInspectable var textColor: NSColor?
    
        override func awakeFromNib()
        {
            if let textColor = textColor, let font = font
            {
                let style = NSMutableParagraphStyle()
                style.alignment = .center
    
                let attributes =
                    [
                        NSAttributedString.Key.foregroundColor: textColor,
                        NSAttributedString.Key.font: font,
                        NSAttributedString.Key.paragraphStyle: style
                        ] as [NSAttributedString.Key : Any]
    
                let attributedTitle = NSAttributedString(string: title, attributes: attributes)
                self.attributedTitle = attributedTitle
            }
        }
    
        override func draw(_ dirtyRect: NSRect)
        {
            super.draw(dirtyRect)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 2012-02-05
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多