UILabel
根据内容计算高度, 设置上下左右的间距
/// 1,给label设置要显示的字体,
self.label.text = @"你这个方法是在多个字体的时候又效果,如果说label很大,字体的个数很少,你这个设置的方法是在label的中心靠左边显示的,没有达到左上角显示字体的效果,我当时是用了label的自适应来写的,不知道你们还有有好的方法,希望可以讨论一下~,字体的个数很少,你这个设置的方法是在label的中心靠左边显示的,没有达到左上角显示字体的效果,我当时是用了label的自适应来写的,不知道你们还有有好的方法,希望可以讨论一下~";
/// 2, 给一个固定的宽度
self.label.frame = CGRectMake(10 , 10, kScreenW-40, 0);
/// 3, 通过宽度和字体算出高度
CGSize size = [self.label sizeThatFits:CGSizeMake(kScreenW-40, 0)];
/// 4, 设置label的frame
self.label.frame = CGRectMake(10, 10, size.width, size.height);
设置
self.label.yf_contentInsets = UIEdgeInsetsMake(10, 10, 10, 10);
效果如下
不设置 如下
UILabel
添加分类后可以直接调用上述方法
.h 文件
#import <UIKit/UIKit.h>
@interface UILabel (YFAdd)
/**
修改label内容距 `top` `left` `bottom` `right` 边距
*/
@property (nonatomic, assign) UIEdgeInsets yf_contentInsets;
@end
.m文件
#import "UILabel+YFAdd.h"
#import <objc/runtime.h>
/// 获取UIEdgeInsets在水平方向上的值
CG_INLINE CGFloat
UIEdgeInsetsGetHorizontalValue(UIEdgeInsets insets) {
return insets.left + insets.right;
}
/// 获取UIEdgeInsets在垂直方向上的值
CG_INLINE CGFloat
UIEdgeInsetsGetVerticalValue(UIEdgeInsets insets) {
return insets.top + insets.bottom;
}
CG_INLINE void
ReplaceMethod(Class _class, SEL _originSelector, SEL _newSelector) {
Method oriMethod = class_getInstanceMethod(_class, _originSelector);
Method newMethod = class_getInstanceMethod(_class, _newSelector);
BOOL isAddedMethod = class_addMethod(_class, _originSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
if (isAddedMethod) {
class_replaceMethod(_class, _newSelector, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
} else {
method_exchangeImplementations(oriMethod, newMethod);
}
}
@implementation UILabel (YFAdd)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ReplaceMethod([self class], @selector(drawTextInRect:), @selector(yf_drawTextInRect:));
ReplaceMethod([self class], @selector(sizeThatFits:), @selector(yf_sizeThatFits:));
});
}
- (void)yf_drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = self.yf_contentInsets;
[self yf_drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
- (CGSize)yf_sizeThatFits:(CGSize)size {
UIEdgeInsets insets = self.yf_contentInsets;
size = [self yf_sizeThatFits:CGSizeMake(size.width - UIEdgeInsetsGetHorizontalValue(insets), size.height-UIEdgeInsetsGetVerticalValue(insets))];
size.width += UIEdgeInsetsGetHorizontalValue(insets);
size.height += UIEdgeInsetsGetVerticalValue(insets);
return size;
}
const void *kAssociatedYf_contentInsets;
- (void)setYf_contentInsets:(UIEdgeInsets)yf_contentInsets {
objc_setAssociatedObject(self, &kAssociatedYf_contentInsets, [NSValue valueWithUIEdgeInsets:yf_contentInsets] , OBJC_ASSOCIATION_RETAIN);
}
- (UIEdgeInsets)yf_contentInsets {
return [objc_getAssociatedObject(self, &kAssociatedYf_contentInsets) UIEdgeInsetsValue];
}