如何使用NSAttributedString在Swift中对大字体的文本加下划线?

时间:2019-02-19 17:54:21

标签: fonts swift4 nsattributedstring

我不知道如何在swift 4.2中使用NSAttributedString在大字体的文本下划线

例如,此代码未带下划线,但是如果我将字体大小更改为12或更小,它将起作用并且文本将带下划线。

我如何在字体大小为25或更大的文字下划线?

import SpriteKit

class GameScene: SKScene {

    let mylabel = SKLabelNode()

    override func didMove(to view: SKView) {

        let myAttributes : [NSAttributedString.Key: Any] = [
            NSAttributedString.Key.font : UIFont(name: "ChalkboardSE-Regular", size: 25.0)!,
            NSAttributedString.Key.underlineStyle : NSUnderlineStyle.single.rawValue]

        mylabel.attributedText = NSMutableAttributedString(string: "Hello World", attributes: myAttributes)
        mylabel.position = CGPoint(x: UIScreen.main.bounds.width/2 , y: UIScreen.main.bounds.height/2)
        addChild(mylabel)
    }
}

1 个答案:

答案 0 :(得分:0)

class UnderlinedLabel: UILabel {

    override var text: String? {
        didSet {
            guard let text = text else { return }
            let textRange = NSMakeRange(0, text.count)
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSAttributedString.Key.underlineStyle , value: NSUnderlineStyle.single.rawValue, range: textRange)
            // Add other attributes if needed
            self.attributedText = attributedText
        }
    }
}

之后,直接将UnderlineLabel类分配给特定的Label到StoryBoard中。

相关问题