首页 技术 正文
技术 2022年11月15日
0 收藏 760 点赞 2,535 浏览 1203 个字

iOS UILabel控件默认文字位置是居中的,如图所示:

iOS UILabel 文字 置顶/置底 实现

但是我们经常碰到这样的需求,希望文字向上置顶,或者向下置底,但是很遗憾,iOS API中并没有提供相应的属性和方法,需要我们手动设置。

利用 分类(category)为UILabel添加属性 isTop 和 isBottom来控制文字是否置顶和置底。

实现:利用往文字后面活前面下面添加”\n”来实现文字填充满整个UILable控件实现置顶/置顶效果

.h文件

#import <UIKit/UIKit.h>@interface UILabel (TextAlign)@property (nonatomic, assign) BOOL isTop;
@property (nonatomic, assign) BOOL isBottom;@end

.m文件

#import "UILabel+TextAlign.h"@implementation UILabel (TextAlign)-(void)setIsTop:(BOOL)isTop {    if (isTop) {        CGSize fontSize = [self.text sizeWithFont:self.font];
//控件的高度除以一行文字的高度
int num = self.frame.size.height/fontSize.height;
//计算需要添加换行符个数
int newLinesToPad = num - self.numberOfLines;
self.numberOfLines = 0;
for(int i=0; i<newLinesToPad; i++)
//在文字后面添加换行符"/n"
self.text = [self.text stringByAppendingString:@"\n"];
}
}-(void)setIsBottom:(BOOL)isBottom { if (isBottom) {
CGSize fontSize = [self.text sizeWithFont:self.font];
//控件的高度除以一行文字的高度
int num = self.frame.size.height/fontSize.height;
//计算需要添加换行符个数
int newLinesToPad = num - self.numberOfLines;
self.numberOfLines = 0;
for(int i=0; i<newLinesToPad; i++)
//在文字前面添加换行符"/n"
self.text = [NSString stringWithFormat:@" \n%@",self.text];
}
}@end

使用方法: 
导入头文件

#import "UILabel+TextAlign.h"

然后设置属性


//置顶
self.lb.isTop = YES;//置底
self.lb.isBottom = YES;
源码免费下载地址:http://www.jinhusns.com/Products/Download/

iOS UILabel 文字 置顶/置底 实现

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,030
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,859