使用 Swift 在 NSTextField 中垂直对齐文本 [英] Vertically aligning text in an NSTextField using Swift
问题描述
我一直在阅读有关如何在 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?
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屋!