免费开源的iOS开发学习平台

UILabel详解:1-UILabel简介

UILabel是iOS开发中最经常使用的基础控件之一,它可以用来显示静态的单行或多行文本,不可编辑。UILabel继承自UIView,因此UIView中的所有方法和属性UILabel都具备。除此之外,UILabel还具备一些其特殊的方法和属性,主要是针对显示文本的样式和内容,在实际开发过程中需要掌握。

常用属性介绍

  • 设置标签显示文本。
@property(nullable, nonatomic,copy) NSString  *text; 
  • 设置文本字体和字体大小(系统字体默认大小为17)。
@property(null_resettable, nonatomic,strong) UIFont *font; 
  • 设置文本颜色。
@property(null_resettable, nonatomic,strong) UIColor *textColor; 
  • 设置文本背景颜色。
@property(nullable, nonatomic,copy) UIColor *backgroundColor;
  • 设置文本对齐方式,默认居左(NSTextAlignmentLeft),除此之外,还可以选择居中(NSTextAlignmentCenter)、居右(NSTextAlignmentRight)。
@property(nonatomic) NSTextAlignment textAlignment;
  • 设置超出label边界文字的截取方式。(默认省略结尾)。
@property(nonatomic)  NSLineBreakMode    lineBreakMode;
  • 设置文本是否可高亮。
@property(nonatomic,getter=isHighlighted) BOOL  highlighted; 
  • 设置用于渲染文本的最大行数。
@property(nonatomic) NSInteger numberOfLines;

UILabel标签的创建

当我们需要创建一个UILabel标签时,我们可以通过代码以及Xib的方式进行添加。

当使用代码创建UILabel类的对象时,我们可以使用alloc以及initWithFrame:方法得到一个UILabel对象,然后对该标签对象的外观属性进行设置。

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建UILabel对象并设置属性
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 250, 50)];
    label.backgroundColor = [UIColor redColor];
    label.textColor = [UIColor whiteColor];
    label.text = @"www.99ios.com";
    label.font = [UIFont systemFontOfSize:20];
    label.textAlignment = NSTextAlignmentCenter;
    //添加到控制器View
    [self.view addSubview:label];
}

运行结果如下。可以得到一个标签对象,该标签的背景颜色为红色,文字居中,字体颜色为白色,20号字体。

除了使用代码创建之外,我们还可以通过Xib的方式通过界面来添加。例如,我们在Storyboard中,添加一个样式完全相同的标签,并对标签的属性进行设置。

示例代码

https://github.com/99ios/7.5.1