iOS UILabel控件

UILabel是iOS中最基本的一个控件,用来展示一段不可编辑的文本。UILabel继承于UIView,包含继承于UIView的属性,可查看iOS UIView控件

1. UILabel的主要属性

// 显示文本
@property(nullable, nonatomic,copy) NSString *text;
// 文本的颜色,默认为黑色
@property(null_resettable, nonatomic,strong) UIColor *textColor;
// 字体以及大小,默认为系统字体
@property(null_resettable, nonatomic,strong) UIFont *font;

// 文字的对齐方式,默认是NSTextAlignmentLeft左对齐
@property(nonatomic) NSTextAlignment textAlignment;
// 文字长度超出范围时文字的显示方式
@property(nonatomic) NSLineBreakMode lineBreakMode;
// 文本显示的行数,设置为0 即为自动换行
@property(nonatomic) NSInteger numberOfLines;
// 默认是YES,设置为NO将会使文本变暗,表示它没有激活
@property(nonatomic,getter=isEnabled) BOOL enabled;

// 文本高亮颜色
@property(nullable, nonatomic,strong)UIColor *highlightedTextColor;
// 是否高亮显示
@property(nonatomic,getter=isHighlighted) BOOL highlighted; 

// 阴影颜色
@property(nullable, nonatomic,strong) UIColor *shadowColor;
// 阴影偏移量,默认是(0, -1)
@property(nonatomic) CGSize shadowOffset;

// 根据宽度调整font,默认为NO
@property(nonatomic) BOOL adjustsFontSizeToFitWidth;
// 最小收缩比例
@property(nonatomic) CGFloat minimumScaleFactor;

// 标签属性文本
@property(nullable, nonatomic,copy) NSAttributedString *attributedText;

标签属性文本,详见iOS AttributedString简介

textAlignment对齐方式

对齐方式说明
NSTextAlignmentLeft左对齐
NSTextAlignmentRight右对齐
NSTextAlignmentCenter居中

显示如下
在这里插入图片描述
lineBreakMode显示方式

显示方式说明
NSLineBreakByTruncatingHead缩略头部
NSLineBreakByTruncatingTail缩略尾部
NSLineBreakByTruncatingMiddle缩略中部
NSLineBreakByWordWrapping以空格为边界,保留单词
NSLineBreakByCharWrapping保留整个字符
NSLineBreakByClipping简单剪裁,到边界截断

下图中,第一条是默认显示
在这里插入图片描述
numberOfLines设置为0
在这里插入图片描述
adjustsFontSizeToFitWidth设置为YES
在这里插入图片描述
enabled设置为NO
在这里插入图片描述
highlightedTextColor设置为[UIColor redColor]highlighted设置为YES
在这里插入图片描述
下图中,第一条是正常情况,第二条ShadowColor设置为[UIColor magentaColor]ShadowOffset设置为(10, 5)
在这里插入图片描述

2. UILabel高度计算

boundingRectWithSize:options:attributes:context:计算文本高度

NSString *text = @"Copyright (c) 2006-2018 Apple Inc. All rights reserved.";

UILabel *boundsLabel = [[UILabel alloc] init];
boundsLabel.backgroundColor = [UIColor brownColor];
boundsLabel.text = text;
boundsLabel.numberOfLines = 0;
boundsLabel.font = [UIFont systemFontOfSize:17];

NSInteger option = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
CGRect rect = [text boundingRectWithSize:CGSizeMake(320, CGFLOAT_MAX) options:option 
            attributes:@{NSFontAttributeName: boundsLabel.font} context:nil];

boundsLabel.frame = CGRectMake(30, 100, 320, ceilf(rect.size.height) + 1);
[self.view addSubview:boundsLabel];

显示如下
在这里插入图片描述

相关文章
iOS UILabel控件
iOS AttributedString简介
iOS UIFont简介

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值