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

查看:227
本文介绍了使用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:

  • http://www.cocoabuilder.com/archive/cocoa/174994-repositioning-an-nstextfieldcell.html
  • https://red-sweater.com/blog/148/what-a-difference-a-cell-makes
  • Vertically Centre Text in NSSecureTextField with subclassing
  • Get NSTextField contents to scale
  • vertically align text in a CATextLayer?

我在Swift中尝试过的一件事是设置以下属性:

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!

推荐答案

这很难做到,因为Apple很难做到这一点.我通过子类化NSTextFieldCell并重写了drawingRectForBounds:这样的方法来实现它:

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)
}

这只是我的方法,我敢肯定还有更好的方法,但我还不知道.这仅适用于TextFields中的标准字体大小(文本高度为22).这就是为什么我将其硬编码.还没有弄清楚如何更改字体后如何获得单元格中的高度.

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.

结果:

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

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