NSTextView如何使文本位于行的中间

时间:2017-08-03 18:20:39

标签: swift macos nstextview

class ViewController: NSViewController {
    @IBOutlet var editView: NSTextView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let
        paragraphStyle = NSParagraphStyle.default().mutableCopy() as! NSMutableParagraphStyle
        paragraphStyle.lineHeightMultiple = 1.6
        editView.defaultParagraphStyle = paragraphStyle;
        //editView.typingAttributes[NSFontAttributeName] = paragraphStyle;
        editView.typingAttributes[NSParagraphStyleAttributeName] = paragraphStyle;

    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}

这是我的所有代码,在main.storyboard中,只有一个NSTextView控件。

但是我的文字被绘制了,而这一切都是从行的底部开始的,这不是我想要的。我希望能够将文本保持在行的垂直位置。我在这方面没有找到案例,请帮我解答。谢谢

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用NSAttributedStringKey.baselineOffset(Swift 3中的NSBaselineOffsetAttributeName)来调整行内文本的垂直位置。您当然需要编写一些代码来计算行高并找到要使用的正确基线,但是这段代码示例应该为您提供基本的想法:

class ViewController: NSViewController {
    @IBOutlet var editView: NSTextView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
        paragraphStyle.lineHeightMultiple = 1.6
        editView.defaultParagraphStyle = paragraphStyle
        editView.typingAttributes[.paragraphStyle] = paragraphStyle
        editView.typingAttributes[.baselineOffset] = 15
    }

    override var representedObject: Any? {
        didSet {
            // Update the view, if already loaded.
        }
    }
}