如何使用NSAttributedString将多行文本添加到NSButton?

时间:2018-04-27 11:23:48

标签: swift xcode macos nsattributedstring nsbutton

我的应用程序支持多种语言。我有一个Translation对象,它在NSButton Title上设置字符串。如何使用多行在Button中设置文本? 我使用self.lineBreakMode = .ByWordWrapping但它不起作用。

class CustomNSButton: NSButton {

override func viewWillDraw() {
    let currentText = Translations.shared.current?[self.identifier ?? ""]?.string ?? self.stringValue
    self.lineBreakMode = .byWordWrapping
    let size  = calculateIdealFontSize(min: 5, max: 16)
    let translatedString = CustomFormatter.string(for: currentText)
    let pstyle = NSMutableParagraphStyle()
    pstyle.alignment = .center
    let translatedAttributedString = CustomFormatter.attributedString(for: translatedString ?? "", withDefaultAttributes:[NSFontAttributeName : NSFont(name: (self.font?.fontName)!, size: CGFloat(size))!, NSParagraphStyleAttributeName : pstyle])!
    attributedTitle = translatedAttributedString
}
}

1 个答案:

答案 0 :(得分:0)

我使用let textLabel = NSTextField()let textFieldCell = CustomNSTextFieldCell()子类创建了多行文字。在CustomNSButtonaddSubview(textLabel)

中添加子视图
class CustomNSButton: NSButton {

    let textLabel = NSTextField()
    let textFieldCell = CustomNSTextFieldCell()

    override func viewWillDraw() {
        textLabel.frame = CGRect(x:0,y:0, width: frame.width - 2, height: frame.height - 2)
        let pstyle = NSMutableParagraphStyle()
        pstyle.alignment = .center
        textLabel.attributedStringValue = CustomFormatter.attributedString(for: translatedString ?? "", withDefaultAttributes:[NSFontAttributeName : NSFont(name: (self.font?.fontName)!, size: CGFloat(size))!, NSParagraphStyleAttributeName : pstyle, NSForegroundColorAttributeName : NSColor.white])!
        textLabel.isEditable = false
        textLabel.isBezeled = false
        textLabel.backgroundColor = NSColor.clear
        textLabel.cell = textFieldCell
        addSubview(textLabel)
    }
}


class CustomNSTextFieldCell: NSTextFieldCell {

    override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
        let attrString: NSAttributedString? = attributedStringValue
        attrString?.draw(with: titleRect(forBounds: cellFrame), options: [.truncatesLastVisibleLine, .usesLineFragmentOrigin])
    }

    override func titleRect(forBounds theRect: NSRect) -> NSRect {
        var tFrame: NSRect = super.titleRect(forBounds: theRect)
        let attrString: NSAttributedString? = attributedStringValue
        let tRect: NSRect? = attrString?.boundingRect(with: tFrame.size, options: [.truncatesLastVisibleLine, .usesLineFragmentOrigin])
        if (textRect?.size.height)! < tFrame.size.height {
            tFrame.origin.y = theRect.origin.y + (theRect.size.height - (textRect?.size.height)!) / 2.0
            tFrame.size.height = (textRect?.size.height)!
        }
        return tFrame
    }
}