自定义UILabel设置垂直方向的居上,居中,居下
IOS系统框架中UILabel的属性textAlignment只调整水平方向的居中,居左,居右,而没有垂直方向的调整。所以要自定义一个继承自UILabel的类,在类的实现文件中进行文字的重绘,达到垂直方向的位置调整。
新建一个类文件,继承自UILabel,头文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #import <UIKit/UIKit.h> typedef NS_ENUM ( NSInteger ,VerticalAlignment){ VerticalAlignmentTop, VerticalAlignmentMiddle, VerticalAlignmentBottom }; @interface FSVerticallyAlignedLabel : UILabel @property ( nonatomic ,assign) VerticalAlignment verticalAlignment; @end |
在.m文件中,实现verticalAlignment的设置方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | @implementation FSVerticallyAlignedLabel - ( id )initWithFrame:(CGRect)frame { if ( self = [ super initWithFrame:frame]) { self .verticalAlignment = VerticalAlignmentMiddle; } return self ; } /** * 设置属性方法 * * @param verticalAlignment 垂直调整位置 */ - ( void )setVerticalAlignment:(VerticalAlignment)verticalAlignment { _verticalAlignment = verticalAlignment; [ self setNeedsDisplay]; } /** * 计算文字的矩形区域 * * @param bounds label矩形区域 * @param numberOfLines 行数 * * @return 返回文字所占的矩形区域 */ - (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:( NSInteger )numberOfLines { CGRect textRect = [ super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines]; //通过设定字体区域的y值来调整垂直位置 switch ( self .verticalAlignment) { case VerticalAlignmentTop: textRect.origin.y = bounds.origin.y; break ; case VerticalAlignmentMiddle: textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0; break ; case VerticalAlignmentBottom: textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height; break ; } return textRect; } //重写父类方法 - ( void )drawTextInRect:(CGRect)rect { CGRect actualRect = [ self textRectForBounds:rect limitedToNumberOfLines: self .numberOfLines]; [ super drawTextInRect:actualRect]; } @end |
分类:
IOS开发
标签:
UILabel垂直居中
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 提示词工程师自白:我如何用一个技巧解放自己的生产力
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 如何不购买域名在云服务器上搭建HTTPS服务