vertically aligning text in NSTableView row

前端 未结 4 1103
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 12:47

I have a small problem with NSTableView. When I am increasing height of a row in table, the text in it is aligned at top of row but I want to align it vertically centered!

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 13:05

    Here is the Swift version of the code building on the answer above:

    import Foundation
    import Cocoa
    
    class VerticallyCenteredTextField : NSTextFieldCell
    {
    
        override func titleRectForBounds(theRect: NSRect) -> NSRect
        {
            var titleFrame = super.titleRectForBounds(theRect)
            var titleSize = self.attributedStringValue.size
            titleFrame.origin.y = theRect.origin.y - 1.0 + (theRect.size.height - titleSize.height) / 2.0
            return titleFrame
        }
    
        override func drawInteriorWithFrame(cellFrame: NSRect, inView controlView: NSView)
        {
            var titleRect = self.titleRectForBounds(cellFrame)
    
            self.attributedStringValue.drawInRect(titleRect)
        }
    }
    

    Then I set the height of the tableView heightOfRow in the NSTableView:

    func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat
    {
        return 30
    }
    

    Set the class of the NSTextFieldCell to be VerticallyCenteredTextField:

    enter image description here

    and the height of the TableViewCell

    enter image description here

    enter image description here

    Thanks Bryan for your help.

提交回复
热议问题