如何设置UILabel的内边距

2025-04-06 18:16:19
推荐回答(2个)
回答1:

最近在项目中,有个地方需要设置UILabel的内边距,即字体和Label控件之间的间隙。UILabel不像UIButton那样,有个contentEdgeInsets、titleEdgeInsets、imageEdgeInsets供我们设置文字或图片与按钮边界的界限,所以我们只能另外想其他办法来实现。其实,办法也很简单,只需要我们自定义UILabel,然后重写drawTextInRect:方法即可实现我们的目标。
CustomLabel.h

#import

@interface CustomLabel : UILabel

@property (nonatomic, assign) UIEdgeInsets textInsets; // 控制字体与控件边界的间隙

@end
CustomLabel.m

#import "CustomLabel.h"

@implementation CustomLabel

- (instancetype)init {
if (self = [super init]) {
_textInsets = UIEdgeInsetsZero;
}
return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_textInsets = UIEdgeInsetsZero;
}
return self;
}

- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, _textInsets)];
}

@end
Demo.m

CustomLabel *titleLabel = [[CustomLabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.f, 24.0f)];
titleLabel.backgroundColor = [UIColor whiteColor];
titleLabel.textColor = [UIColor blackColor];
titleLabel.font = [UIFont systemFontOfSize:12.0f];
titleLabel.textInsets = UIEdgeInsetsMake(0.f, 15.f, 0.f, 0.f); // 设置左内边距

回答2:

系统的UILabel附上文字后后自动给出一定的内边距,按照UI的设计图需求,标签附着文字后不能留有边距,只能自己自定义一个没有内边距的UILabel。