网上查找了好几篇案例,要不Cell的大小改变了,要不背景颜色改变了,但其中有一篇写的挺好的,大家可以看一下:
macOS 开发之 NSTextField 文本的垂直居中 (smslit.cn)
下面是记录使用的方法:
新建一个项目:
在界面中拉进一个Label控件,为了方便观察,将Display勾选上,同时一定要将Border选上,不能默认选择第一个,如果选第一个,居中会失败,切记!!!
新建一个NSTextFieldCell的类VerticalTextFieldCell:
重写NSTextFieldCell的drawingRect方法:(上面之所以Border之所以要选择,是因为不选择的话,进不去这个方法)
import Cocoa
class VerticalTextFieldCell: NSTextFieldCell {
override func drawingRect(forBounds theRect: NSRect) -> NSRect {
var newRect:NSRect = super.drawingRect(forBounds: theRect)
let textSize:NSSize = self.cellSize(forBounds: theRect)
let heightDelta:CGFloat = newRect.size.height - textSize.height
if heightDelta > 0 {
newRect.size.height = textSize.height
newRect.origin.y += heightDelta * 0.5
}
return newRect
}
}
将界面上的Label的cell的Class选择为VerticalTextFieldCell:
运行后:
为什么不像原文那样直接在原有的类中创建一个类,是为了方便其它项目的使用,个人喜欢吧,文章仅仅作为记录。
如果有谁看到这篇文章,刚好知道更好的方法,或者Border在不选择的情况下,也能实现这种效果,麻烦告诉我一下,谢谢!
如果使用OC语言,可以改成:
- (NSRect)drawingRectForBounds:(NSRect)rect {
NSRect newRect = [super drawingRectForBounds:rect];
NSSize textSize = [self cellSizeForBounds:rect];
CGFloat heightDelta = newRect.size.height - textSize.height;
if (heightDelta > 0) {
newRect.size.height = textSize.height;
newRect.origin.y += heightDelta * 0.5;
}
return newRect;
}