UILabel不像别的UI控件,可以通过设置edgeInset
属性来控制文字、图片与边缘的距离。
但是我们可以通过自定义Label,重写drawTextInRect
的方式来实现。
核心代码:
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, _textInsets)];
}
通过添加属性值textInsets
,达到动态控制的效果。
完整代码参考
头文件:
#import <UIKit/UIKit.h>
@interface KDOHLabel : UILabel
@property (nonatomic, assign) UIEdgeInsets textInsets;
@end
实现文件:
#import "KDOHLabel.h"
@implementation KDOHLabel
- (instancetype)init {
if (self = [super init]) {
_textInsets = UIEdgeInsetsZero;
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_textInsets = UIEdgeInsetsZero;
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
_textInsets = UIEdgeInsetsZero;
}
return self;
}
#pragma mark - Override
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, _textInsets)];
}
@end
网友评论