使用InspectableDesignable属性改变NSButton的字体。

问题描述 投票:0回答:1

我不知道该怎么做。我找到了一个自定义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个回答
0
投票

我想我找到了一个解决方案。似乎可以用。我正在寻找一种方法来制作一个非斜面的按钮,以便在点击时进行适当的高亮显示,但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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.