UIKit之UILabel篇

1.初始化控件(文本控件)

UILabel *etlbl = [[UILable alloc]init];


2.设置基本属性及用法

  1. frame:设置UILable的显示起点坐标(x,y)和宽高(width,height)

etlbl.frame = CGRectMake(<#x起点#>, <#y起点#>, <#宽度#>,<#高度#>);

  1. text:设置文本控件的内容(即文字显示的内容)

etlbl.text = @"文字显示内容";

  1. font:文字字体大小及类型(常规,加粗,细小等)

etlbl.font = [UIFont systemFontOfSize:15];

  1. textColor:文字颜色

etlbl.textColor = [UIColor greenColor];

  1. shadowOffSet:阴影的大小

x轴及y轴的偏移量
etlbl.shadowOffset = CGSizeMake(5, 5);

  1. shadowColor:阴影部分颜色

etlbl.shadowColor = [UIColor yellowColor];

  1. textAlignment:文字的对其方式(剧中,左对齐,右对齐),系统默认的三种方式

etlbl.textAlignment = NSTextAlignmentCenter; //中心对齐(默认横向对齐)
etlbl.textAlignment = NSTextAlignmentRight; //文字靠右对齐
etlbl.textAlignment = NSTextAlignmentLeft; //文字靠左对齐

  1. lineBreakMode
  2. attributedText:可以自定义某部分显示大小和颜色

配合 NSMutableAttributedString属性介绍及使用

/**********属性方法***********/
//为某一范围内文字设置多个属性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
//为某一范围内文字添加某个属性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
//为某一范围内文字添加多个属性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
//移除某范围内的某个属性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
/**********常用属性keys***********/
NSFontAttributeName             //字体
NSParagraphStyleAttributeName   //段落格式 
NSForegroundColorAttributeName  //字体颜色
NSBackgroundColorAttributeName  //背景颜色
NSStrikethroughStyleAttributeName//删除线格式
NSUnderlineStyleAttributeName    //下划线格式
NSStrokeColorAttributeName       //删除线颜色
NSStrokeWidthAttributeName       //删除线宽度
NSShadowAttributeName            //阴影

全部NSMutableAttributedString属性,key and value

//***********keys***********************************Value****************************************//
    NSFontAttributeName;                  //字体,value是UIFont对象
    NSParagraphStyleAttributeName;        //绘图的风格(居中,换行模式,间距等诸多风格),value是NSParagraphStyle对象
    NSForegroundColorAttributeName;       // 文字颜色,value是UIFont对象
    NSBackgroundColorAttributeName;       // 背景色,value是UIFont
    NSLigatureAttributeName;              //  字符连体,value是NSNumber
    NSKernAttributeName;                  // 字符间隔
    NSStrikethroughStyleAttributeName;    //删除线,value是NSNumber
    NSUnderlineStyleAttributeName;        //下划线,value是NSNumber
    NSStrokeColorAttributeName;           //描绘边颜色,value是UIColor
    NSStrokeWidthAttributeName;           //描边宽度,value是NSNumber
    NSShadowAttributeName;                //阴影,value是NSShadow对象
    NSTextEffectAttributeName;            //文字效果,value是NSString
    NSAttachmentAttributeName;            //附属,value是NSTextAttachment 对象
    NSLinkAttributeName;                  //链接,value是NSURL or NSString
    NSBaselineOffsetAttributeName;        //基础偏移量,value是NSNumber对象
    NSUnderlineColorAttributeName;        //下划线颜色,value是UIColor对象
    NSStrikethroughColorAttributeName;    //删除线颜色,value是UIColor
    NSObliquenessAttributeName;           //字体倾斜
    NSExpansionAttributeName;             //字体扁平化
    NSVerticalGlyphFormAttributeName;     //垂直或者水平,value是 NSNumber,0表示水平,1垂直
/*****************************************************************************************************/

基本用法如下:

/************************************************某区域内************************************************************/
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:@"0元"];
 [string setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(string.length-1, 1)];
 etlbl.attributedText = string;
/************************************************基本用法************************************************************/
    NSString *content = @"内容太多,需要自适应才能解决问题,所以需要写这个扩展类,内容太多,需要自适应才能解决问题,所以需要写这个扩展类";

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:content];
    //字体大小
    [string addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:10]
                   range:NSMakeRange(0, 1)];
    //字体颜色
    [string addAttribute:NSForegroundColorAttributeName
                   value:[UIColor yellowColor]
                   range:NSMakeRange(1, 1)];
    //字体背景颜色
    [string addAttribute:NSBackgroundColorAttributeName
                   value:[UIColor purpleColor]
                   range:NSMakeRange(2, 1)];

    //添加下划线
    [string addAttribute:NSUnderlineStyleAttributeName
                   value:@(NSUnderlineStyleSingle)
                   range:NSMakeRange(3, 1)];
    //添加下划线颜色
    [string addAttribute:NSUnderlineColorAttributeName
                   value:[UIColor redColor]
                   range:NSMakeRange(3, 1)];
    
    
    UILabel *etlbl3 = [[UILabel alloc]initWithFrame:CGRectMake(100, 400, 200, 30)];
    etlbl3.attributedText = string;
    [self.view addSubview:etlbl3];
/************************************************基本用法************************************************************/

  • userInteractionEnabled:设置是否可以用户交互,默认NO;一般应用于文本控件添加触摸手势
  • numberOfLines:设置文本可以显示的行数,默认1行;如果需要自适应文本高度需要设置0行
  • 最后需要将控件添加到父视图上
    *补充:富文本中间横线(效果及代码如下)


    中间横线.png
#define SystemVersion [[[UIDevice currentDevice] systemVersion] floatValue]

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *str = [NSString stringWithFormat:@"%.1f", 9999.0];
    
    NSRange strRange1 = {[@"京东价:" length], [str length]};
    
    NSMutableAttributedString *attributeMarket = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", @"京东价:", str]];
    
    if (SystemVersion >= 10.3) {
        
        [attributeMarket addAttribute:NSStrikethroughStyleAttributeName
                                value:@(NSUnderlineStyleSingle)
                                range:strRange1];
        
        [attributeMarket addAttribute:NSBaselineOffsetAttributeName
                                value:@(NSUnderlineStyleNone)
                                range:strRange1];
    } else {
        
        [attributeMarket addAttribute:NSStrikethroughStyleAttributeName
                                value:[NSNumber numberWithInteger:NSUnderlineStyleSingle]
                                range:strRange1];
    }
    
    [attributeMarket addAttribute:NSForegroundColorAttributeName
                            value:[UIColor redColor]
                            range:strRange1];

    UILabel *etlbl3 = [[UILabel alloc]initWithFrame:CGRectMake(20, 200, CGRectGetWidth(self.view.frame)-40, 30)];
    
    etlbl3.attributedText = attributeMarket;
    
    [self.view addSubview:etlbl3];
}

3.特殊用法

1.自适应高度或者宽度

UILable扩展类及使用方法:
etlbl.text = @"内容太多,需要自适应才能解决问题,所以需要写这个扩展类";
[etlbl setAutoHeigh];

typedef enum : NSUInteger {
    NSTextAlignmentVertailTop,
    NSTextAlignmentVertailTypeMiddle,//defalut
    NSTextAlignmentVertailTypeBottom,
} NSTextAlignmentVertailType;

@interface UILabel (Extern)

/**
 *  自动设置高度
 */
- (void)setAutoHeigh;

/**
 *  设置垂直方向对齐
 *
 *  @param textAlignment 对齐方式
 */
- (void)setTextAlginVertail:(NSTextAlignmentVertailType)textAlignment;

/**
 *  获取textContent内容所需要的尺寸
 *
 *  @return size
 */
- (CGSize)getContentSize;

@end


@implementation UILabel (Extern)
- (void)setAutoHeigh{
    NSAssert(self.frame.size.width==0||self.frame.size.height==0?nil:@"", @"请设置UILable的width或者Height");
    
    [self setNumberOfLines:0];
    CGSize size =  [self.text boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT)
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:@{NSFontAttributeName:self.font}
                                           context:nil].size;
    self.frame =  CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, size.height);
}
- (void)setTextAlginVertail:(NSTextAlignmentVertailType)textAlignment{
    CGSize fontSize =  [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
    
    double finalHeight = fontSize.height*self.numberOfLines;
    double finalWidth  = self.frame.size.width;
    
    CGSize stringSize = [self.text boundingRectWithSize:CGSizeMake(finalWidth, finalHeight)
                                                options:NSStringDrawingUsesLineFragmentOrigin
                                             attributes:@{NSFontAttributeName:self.font}
                                                context:nil].size;
    
    int newLinesToPad = (finalHeight - stringSize.width) /fontSize.width;
    switch (textAlignment) {
        case NSTextAlignmentVertailTop:{
            for (int i = 0; i

2.获取文本内容所需要的CGSize

NSString的扩展类及用法

    NSString *content = @"内容太多,需要自适应才能解决问题,所以需要写这个扩展类,内容太多,需要自适应才能解决问题,所以需要写这个扩展类";
    UIFont *font = [UIFont systemFontOfSize:15];
    CGFloat maxHeigth = 200;
    CGFloat maxWidht  = 200;
    CGSize size1  = [NSString sizeTextContentMaxHeight:maxHeigth  font:font withContent:content];
    CGSize size2  = [NSString sizeTextContentMaxWidth:maxWidht    font:font withContent:content];
    CGFloat width = [NSString widthTextContentMaxHeight:maxHeigth font:font withContent:content];
    CGFloat height= [NSString heigtTextContentMaxWidth:maxWidht   font:font withContent:content];
@interface NSString (Extern)

/**
 *  计算文本内容的高度(输入宽度,获取高度)
 *
 *  @param width   最大宽度
 *  @param font    字体大小
 *  @param content 文本内容
 *
 *  @return height
 */
+ (CGFloat)heigtTextContentMaxWidth:(CGFloat)maxWidth  font:(UIFont*)font withContent:(NSString*)content;
/**
 *  计算文本内容的宽度(输入高度,获取宽度)
 *
 *  @param width   最大高度
 *  @param font    字体大小
 *  @param content 文本内容
 *
 *  @return width
 */
+ (CGFloat)widthTextContentMaxHeight:(CGFloat)maxHeight font:(UIFont*)font withContent:(NSString*)content;

/**
 *  计算文本内容的尺寸(输入宽度,获取尺寸)
 *
 *  @param width   最大宽度
 *  @param font    字体大小
 *  @param content 文本内容
 *
 *  @return size
 */
+ (CGSize)sizeTextContentMaxWidth:(CGFloat)maxWidth font:(UIFont*)font withContent:(NSString*)content;
/**
 *  计算文本内容的尺寸(输入高度,获取尺寸)
 *
 *  @param height  最大高度
 *  @param font    字体大小
 *  @param content 文本内容
 *
 *  @return size
 */
+ (CGSize)sizeTextContentMaxHeight:(CGFloat)maxheight font:(UIFont*)font withContent:(NSString*)content;

@end

@implementation NSString (Extern)

+ (CGFloat)heigtTextContentMaxWidth:(CGFloat)maxWidth  font:(UIFont*)font withContent:(NSString*)content{
    return [self sizeTextContentMaxWidth:maxWidth font:font withContent:content].height;
}
+ (CGFloat)widthTextContentMaxHeight:(CGFloat)maxHeight font:(UIFont*)font withContent:(NSString*)content{
    return [self sizeTextContentMaxHeight:maxHeight font:font withContent:content].width;
}

+ (CGSize)sizeTextContentMaxWidth:(CGFloat)maxWidth font:(UIFont*)font withContent:(NSString*)content{
    return [content boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT)
                                 options:NSStringDrawingUsesLineFragmentOrigin
                              attributes:@{NSFontAttributeName:font}
                                 context:nil].size;
}
+ (CGSize)sizeTextContentMaxHeight:(CGFloat)maxheight font:(UIFont*)font withContent:(NSString*)content{
    return [content boundingRectWithSize:CGSizeMake(MAXFLOAT,maxheight)
                                 options:NSStringDrawingUsesLineFragmentOrigin
                              attributes:@{NSFontAttributeName:font}
                                 context:nil].size;
}

@end

4.UILabel的居中上中下方向对齐基类

使用方法如下:

TJLabel *etlbl = [[TJLabel alloc]init];
etlbl.frame = CGRectMake(0, 0, 200, 40);
etlbl.text  = @"文字内容";
[etlbl setVerticalAlignment:NSTextVerticalAlignmentBottom];
[self.view addSubview:etlbl];

.h文件

/**
 * UILabel设置居上对齐,居中对齐,居下对齐
 */

typedef NS_ENUM(NSInteger, NSTextVerticalAlignment) {
    NSTextVerticalAlignmentTop = 0,
    NSTextVerticalAlignmentMiddle,
    NSTextVerticalAlignmentBottom
};

@interface TJLabel : UILabel
{
    @private
    NSTextVerticalAlignment _verticalAlignment;
}

@property (nonatomic) NSTextVerticalAlignment verticalAlignment;

@end

.m文件

@implementation TJLabel

@synthesize verticalAlignment = verticalAlignment_;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.verticalAlignment = NSTextVerticalAlignmentMiddle;
    }
    return self;
}

- (void)setVerticalAlignment:(NSTextVerticalAlignment)verticalAlignment {
    verticalAlignment_ = verticalAlignment;
    [self setNeedsDisplay];
}

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
    switch (self.verticalAlignment) {
        case NSTextVerticalAlignmentTop:
            textRect.origin.y = bounds.origin.y;
            break;
        case NSTextVerticalAlignmentBottom:
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
            break;
        case NSTextVerticalAlignmentMiddle:
        default:
            textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
    }
    return textRect;
}

-(void)drawTextInRect:(CGRect)requestedRect {
    CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
    [super drawTextInRect:actualRect];
}
@end

你可能感兴趣的:(UIKit之UILabel篇)