首页 > 其他 > 详细

可以简易设置文字内边距的EdgeInsetsLabel

时间:2014-10-27 17:33:28      阅读:257      评论:0      收藏:0      [点我收藏+]

可以简易设置文字内边距的EdgeInsetsLabel

bubuko.com,布布扣

最终效果:

bubuko.com,布布扣

bubuko.com,布布扣

源码:

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

核心原理:

bubuko.com,布布扣

 

可以简易设置文字内边距的EdgeInsetsLabel

原文:http://www.cnblogs.com/YouXianMing/p/4054535.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!