【Swift】NSTextField如何实现字体居中

网上查找了好几篇案例,要不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;
}

NSTextField实现字体居中-Swift文档类资源-CSDN文库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三岁牧羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值