UILabel文字的顶端显示代码,以及自动换行代码

本文介绍了一种利用Objective-C的Category特性实现UILabel文本顶部和底部对齐的方法,并提供了具体的实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用objective-c的category特性,修改UILabel的绘制代码。示例代码如下
#import <UIKit/UIKit.h>

@interface UILabel (VerticalAlign)

- (void)alignTop;
- (void)alignBottom;

@end


#import "UILabel+VerticalAlign.h"

@implementation UILabel (VerticalAlign)

- (void)alignTop {
    CGSize fontSize = [self.text sizeWithFont:self.font];
    int textOfLine = self.frame.size.height/fontSize.height;
    double finalHeight = fontSize.height * textOfLine;
    double finalWidth = self.frame.size.width;    //expected width of label
    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
    int newLinesToPad = (finalHeight  - theStringSize.height) / fontSize.height;
    for(int i=0; i<newLinesToPad; i++){
        self.text = [self.text stringByAppendingString:@"\n "];
    }
}

- (void)alignBottom {
    CGSize fontSize = [self.text sizeWithFont:self.font];
    int textOfLine = self.frame.size.height/fontSize.height;
    double finalHeight = fontSize.height * textOfLine;
    double finalWidth = self.frame.size.width;    //expected width of label
    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
    int newLinesToPad = (finalHeight  - theStringSize.height) / fontSize.height;
    for(int i=0; i<newLinesToPad; i++)
        self.text = [NSString stringWithFormat:@" \n%@",self.text];
}

@end

使用

[你的label名 alignBottom];

调用

- - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - - 

以下是自动换行

- - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - - 

(省略定义加载relase label的代码)

    CGSize maximumLabelSize = CGSizeMake(150,99999); //先设置一个最大限度

    CGSize expectedLabelSize = [lable.text sizeWithFont:lable.font constrainedToSize:maximumLabelSize lineBreakMode:lable.lineBreakMode];   //设置自动换行,constrainedToSize设置可以接收String的最大值

    label.frame = CGRectMake(20, 20, 150, expectedLabelSize.height);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值