IOS--label的一些属性

1.

label.lineBreakMode = NSLineBreakByCharWrapping;以字符为显示单位显示,后面部分省略不显示。
label.lineBreakMode = NSLineBreakByClipping;剪切与文本宽度相同的内容长度,后半部分被删除。
label.lineBreakMode = NSLineBreakByTruncatingHead;前面部分文字以……方式省略,显示尾部文字内容。
label.lineBreakMode = NSLineBreakByTruncatingMiddle;中间的内容以……方式省略,显示头尾的文字内容。
label.lineBreakMode = NSLineBreakByTruncatingTail;结尾部分的内容以……方式省略,显示头的文字内容。
label.lineBreakMode = NSLineBreakByWordWrapping;以单词为显示单位显示,后面部分省略不显示。

2.label圆角

testlable.layer.cornerRadius = 5.0;
testlable.clipsToBounds = YES;

3.根据label字体大小动态适应宽度,高度固定40px,宽度不固定

// label可设置的最大高度和宽度
   CGSize size = CGSizeMake(SCREEN_W, 40);
//获取当前文本的属性
   NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
//ios7方法,获取文本需要的size,限制宽度
   CGSize  actualsize =[text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
//   更新UILabel的frame
  testlable.frame =CGRectMake((SCREEN_W-actualsize.width)/2,0, actualsize.width, 40);

4.设置内边距,文字与边框的距离

#import <UIKit/UIKit.h>

@interface labelEdge : UILabel

@property (nonatomic, assign) UIEdgeInsets edgeInsets;

@end
#import "labelEdge.h"

@implementation labelEdge

- (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

使用:

labelEdge * testlable = [[labelEdge alloc]initWithFrame:CGRectMake(10,0,200,40)];
testlable.edgeInsets = UIEdgeInsetsMake(8, 10, 8, 10);//设置内边距

 

posted on 2017-07-26 20:53  麦芽呀~  阅读(1330)  评论(0编辑  收藏  举报