可以簡易設置文字內邊距的EdgeInsetsLabel


可以簡易設置文字內邊距的EdgeInsetsLabel

最終效果:

源碼:

EdgeInsetsLabel.h 與 EdgeInsetsLabel.m

//
//  EdgeInsetsLabel.h
//  EdgeInsetsLabel
//
//  Created by YouXianMing on 14/10/27.
//  Copyright (c) 2014年 YouXianMing. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface EdgeInsetsLabel : UILabel

@property(nonatomic, assign) UIEdgeInsets edgeInsets;

@end
//
//  EdgeInsetsLabel.m
//  EdgeInsetsLabel
//
//  Created by YouXianMing on 14/10/27.
//  Copyright (c) 2014年 YouXianMing. All rights reserved.
//

#import "EdgeInsetsLabel.h"

@implementation EdgeInsetsLabel

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    UIEdgeInsets insets = self.edgeInsets;
    CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets)
                    limitedToNumberOfLines:numberOfLines];
    
    rect.origin.x    -= insets.left;
    rect.origin.y    -= insets.top;
    rect.size.width  += (insets.left + insets.right);
    rect.size.height += (insets.top + insets.bottom);
    
    return rect;
}

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

@end

ViewController.m

//
//  ViewController.m
//  SetInsets
//
//  Created by YouXianMing on 14/10/27.
//  Copyright (c) 2014年 YouXianMing. All rights reserved.
//

#import "ViewController.h"
#import "EdgeInsetsLabel.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    EdgeInsetsLabel *label    = [[EdgeInsetsLabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    label.edgeInsets          = UIEdgeInsetsMake(8, 8 + 10, 8, 8 + 10); // 設置內邊距
    label.font                = [UIFont fontWithName:@"HelveticaNeue-Thin" size:30.f];
    label.text                = @"No Zuo No Die";
    [label sizeToFit]; // 重新計算尺寸
    label.layer.cornerRadius  = label.frame.size.height / 2.f;
    label.backgroundColor     = [UIColor blackColor];
    label.textColor           = [UIColor redColor];
    label.layer.masksToBounds = YES;
    label.center              = self.view.center;
    
    [self.view addSubview:label];
}

@end

核心原理:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM