iOS UI入门——使用Objective-C和Swift实现UILabel显示文本

UILabel是很常见的UI控件,用到的地方很多。
Objective-C实现UILabel显示静态文本:

-(void)setupLabel{
    //初始化一个UILabel并确定它的坐标
    UILabel * testLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 130, 120, 40)];
    //设置背景色
    testLabel.backgroundColor = [UIColor orangeColor];
    //设置圆角
    testLabel.layer.cornerRadius = 6;
    testLabel.layer.masksToBounds = YES;
    //设置Label显示的内容
    testLabel.text = @"我是Label";
    //设置字体大小
    testLabel.font = [UIFont systemFontOfSize:16];
    //设置文字在Label上的显示位置
    testLabel.textAlignment = NSTextAlignmentCenter;
    //设置文字颜色
    testLabel.textColor = [UIColor redColor];
    //将Label添加到父self.view上来做显示
    [self.view addSubview:testLabel];
}

Swift实现UILabel显示静态文本:

    func setupLabel() {
        //初始化一个UILabel并确定它的坐标
        let testLabel = UILabel.init(frame: CGRect.init(x: 50, y: 130, width: 120, height: 40))
        //设置背景色
        testLabel.backgroundColor = UIColor.orange
        //设置圆角
        testLabel.layer.cornerRadius = 6
        testLabel.layer.masksToBounds = true
        //设置Label显示的内容
        testLabel.text = "我是Label"
        //设置字体大小
        testLabel.font = UIFont.systemFont(ofSize: 16)
        //设置文字在Label上的显示位置
        testLabel.textAlignment = .center
        //设置文字颜色
        testLabel.textColor = UIColor.red
        //将Label添加到父self.view上来做显示
        self.view.addSubview(testLabel)

    }

以上用到了一些UILabel常用的属性,适合用来显示静态文本且文字显示长度小于Label宽度的,效果图如下:
这里写图片描述
在开发过程中动态显示文本也经常遇到,一种解决方案是让Label自适应文本的大小,添加下面的代码:

//设置Label文字显示的行数
testLabel.numberOfLines = 0;
//设置Label显示的内容
testLabel.text = "总结:串行队列里的任务不能并发执行,只能一个接一个地执行,同一时刻该串行队列里的任务最多只有一个在执行;并发队列里的任务后面的任务不必等待前面的任务执行完毕再执行,可以多个同时执行,同一时刻该并行队列里的任务可以有多个正在执行。"
//Label自适应
testLabel.sizeToFit();

这种方式Label的起始坐标和宽度都不会变,高度会变高来让整个文本都显示下。
效果如图:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/aaaaazq/article/details/80812829