如何一句话为UILabel设置行间距以及字间距

1.为什么要写这样一个分类?

在应用开发过程中,我们经常需要设置Label之间的行间距,以及字间距,每次都是复制粘贴代码,为了摆脱这种累赘,怎么才能在需要的时候只需要调用一次代码就可以实现呢?因此就有了下面的代码:

2.实现原理

为UILabel写了一个分类,UILabel+SNExtension,在头文件中,就添加两个属性。

/**
 *  设置行间距
 */
@property (nonatomic, assign)  CGFloat sn_lineSpace;
/**
 *  设置字体之间的间距
 */
@property (nonatomic, assign)  CGFloat sn_wordSpace;

在私有方法中,

#pragma mark - 利用Runtime为分类添加属性

- (CGFloat)sn_lineSpace
{
    return [objc_getAssociatedObject(self, _cmd) floatValue];
}
- (void)setSn_lineSpace:(CGFloat)sn_lineSpace
{
    objc_setAssociatedObject(self, @selector(sn_lineSpace), @(sn_lineSpace), OBJC_ASSOCIATION_RETAIN);
}
- (CGFloat)sn_wordSpace
{
    return [objc_getAssociatedObject(self, _cmd) floatValue];
}
- (void)setSn_wordSpace:(CGFloat)sn_wordSpace
{
    objc_setAssociatedObject(self, @selector(sn_wordSpace), @(sn_wordSpace), OBJC_ASSOCIATION_RETAIN);
}

在load方法中我们通过 Swizze UIlabel的setText方法:

@implementation UILabel (SNExtension)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
   
        SEL selectors[] = {
            @selector(setText:),
        };
        for (NSUInteger index = 0; index < sizeof(selectors) / sizeof(SEL); ++index) {
            SEL originalSelector = selectors[index];
            SEL swizzledSelector = NSSelectorFromString([@"sn_" stringByAppendingString:NSStringFromSelector(originalSelector)]);
            Method originalMethod = class_getInstanceMethod(self, originalSelector);
            Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
            BOOL addedSuccess = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
            if (addedSuccess)
            {
                class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
            }
            else
            {
                method_exchangeImplementations(originalMethod, swizzledMethod);
            }
        }
    });
}

- (void)sn_setText:(NSString *)text
{
    [self sn_setText:text];
    if (self.sn_lineSpace > 0)
    {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = self.sn_lineSpace;
        paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;
        paragraphStyle.lineBreakMode = self.lineBreakMode;
        paragraphStyle.alignment = self.textAlignment;
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
        [attributedString addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, [self.text length])];

        self.attributedText = attributedString;
    }
    if (self.sn_wordSpace > 0 )
    {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
        [attributedString addAttribute:(__bridge NSString *)kCTKernAttributeName value:@(self.sn_wordSpace) range:NSMakeRange(0, [attributedString length])];
        self.attributedText = attributedString;
    }
}

貌似通过上面的代码就可以解决问题,我们在使用的时候,就可以

 self.contentLabel.sn_lineSpace = 6.f; 

但是这样会有一个问题,就是如果我们是先给Label复制然后在设置行间距是没有问题的,但是如果我们先给Label复制,然后在设置行间距,这个时候这个方法就不会生效。如何解决这个问题呢,我们需要做这样一个操作。我们需要同时swizze layoutSubviews方法,这样就可以了。

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL selectors[] = {
            @selector(setText:),
            @selector(layoutSubviews)
        };
       });
}

- (void)sn_layoutSubviews
{
    [self sn_layoutSubviews];
    if (self.sn_lineSpace > 0)
    {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = self.sn_lineSpace;
        paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;
        //        paragraphStyle.paragraphSpacing = 0.f;
        paragraphStyle.lineBreakMode = self.lineBreakMode;
        paragraphStyle.alignment = self.textAlignment;
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
        [attributedString addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, [self.text length])];
        
        self.attributedText = attributedString;
    }
    if (self.sn_wordSpace > 0 )
    {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
        [attributedString addAttribute:(__bridge NSString *)kCTKernAttributeName value:@(self.sn_wordSpace) range:NSMakeRange(0, [attributedString length])];
        self.attributedText = attributedString;
    }
}

地址:(https://github.com/zwcshy/SNLabel)

你可能感兴趣的:(如何一句话为UILabel设置行间距以及字间距)