objective-c - 在 NSTextField 中设置文本垂直居中

标签 objective-c macos cocoa

NSTextField 在一定高度下,如果文字比较小,布局会是这样

enter image description here

文字流到顶部,如何让文字居中这样:

enter image description here

最佳答案

class CustomTextFieldCell: NSTextFieldCell {

    func adjustedFrame(toVerticallyCenterText rect: NSRect) -> NSRect {
        // super would normally draw text at the top of the cell
        var titleRect = super.titleRect(forBounds: rect)

        let minimumHeight = self.cellSize(forBounds: rect).height
        titleRect.origin.y += (titleRect.height - minimumHeight) / 2
        titleRect.size.height = minimumHeight

        return titleRect
    }

    override func edit(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, event: NSEvent?) {
        super.edit(withFrame: adjustedFrame(toVerticallyCenterText: rect), in: controlView, editor: textObj, delegate: delegate, event: event)
    }

    override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) {
        super.select(withFrame: adjustedFrame(toVerticallyCenterText: rect), in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength)
    }

    override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
        super.drawInterior(withFrame: adjustedFrame(toVerticallyCenterText: cellFrame), in: controlView)
    }

    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
        super.draw(withFrame: cellFrame, in: controlView)
    }
}

关于objective-c - 在 NSTextField 中设置文本垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11775128/

相关文章:

objective-c - 归档构建 .IPA 文件时如何解决位码错误?

ios - 调整 webView 大小时如何修复 webView 的粗糙滚动行为?

php - Apache 服务器上的 500 错误 - "AllowOverride not allowed here"

cocoa - AF网络上传文件

ios - AVPlayer 在 iOS 11 中不可见

ios - 如果我使用委托(delegate)在 View Controller 之间进行通信,我会承担什么风险?

SWIFT 3 OSX Cocoa 阵列 Controller 和 CoreData 绑定(bind) "Search on multiple columns"

cocoa - 从 Nib 名称创建 NSWindow

objective-c - OSX/ cocoa : setting up service in menu for right click and services list

ios - 如何取消Set <AnyCancellable>中的某个特定AnyCancellable?