使用 Swift 在 NSTextField 中垂直对齐文本 [英] Vertically aligning text in an NSTextField using Swift

查看:25
本文介绍了使用 Swift 在 NSTextField 中垂直对齐文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关如何在 NSTextField 上设置垂直对齐的各种选项.我希望文本显示在中心并在 Swift 中以编程方式进行.以下是我目前看过的内容:

  • I have been reading through the various options on how to set the vertical alignment on an NSTextField. I want the text to be displayed in the center and to do it programatically in Swift. Here are the things I have looked so far:

    One thing I have tried in Swift is to set the following property:

    textField.usesSingleLineMode = true
    

    Any tips on the best way to vertically center text would be much appreciated!

    解决方案

    This is very hard to do, as Apple makes this very difficult. I achieved it by subclassing NSTextFieldCell and overriding the drawingRectForBounds: method like so:

    override func drawingRectForBounds(theRect: NSRect) -> NSRect {
        let newRect = NSRect(x: 0, y: (theRect.size.height - 22) / 2, width: theRect.size.width, height: 22)
        return super.drawingRectForBounds(newRect)
    }
    

    This is just my way to do it, I'm sure there are better ways, which I don't know (yet). And this only works for the standard font size in TextFields (which gives a text height of 22). That's why I hardcoded that. Haven't figured out yet, how to get the height in the cell if you change the font.

    Result:

    这篇关于使用 Swift 在 NSTextField 中垂直对齐文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆