UILabel可以在界面创显示一行或者多行文本内容。
UILabel的创建:
(1) 在Stroyboard中使用Ctrl+Drag拖拽法创建
(2) 使用代码创建:UILabel()
[Swift4]
// 设置标签的坐标:x,y 和长宽:width,height let myLabel = UILabel(frame: CGRect(x:10,y:80,width:300,height:100))
// 设置标签的文本内容,使用 n 可以换行 myLabel.text = "Hello,UILabel. n -- (wang123.net)"
// 设置显示文本的行数(默认只显示一行,设为0表示没有行数限制) myLabel.numberOfLines = 2
// 设置标签的背景色 myLabel.backgroundColor = UIColor.white
// 设置标签的文本颜色 myLabel.textColor = UIColor.red
// 设置标签的字体和大小 myLabel.font = UIFont(name: "Helvetica",size: 20)
// 设置对其方式 myLabel.textAlignment = .center
// 对于多行文本自适应高度: mylabel.lineBreakMode= .ByWordWrapping
// 设置显示文本的行数 myLabel.numberOfLines=0
// 设置文本高亮 label.isHighlighted = true //设置文本高亮颜色 label.highlightedTextColor = UIColor.blue
完整的代码示例:
``` //ViewController.swift //运行环境:XcodeVersion 9.1 (9B55) import UIKit
class ViewController: UIViewController {
func showLabel(){ // 设置标签的坐标:x,height let myLabel = UILabel(frame: CGRect(x:10,height:100)); // 设置标签的文本内容,使用 n 可以换行 myLabel.text = "Hello,UILabel. n -- (wang123.net)"; // 设置显示文本的行数(默认只显示一行,设为0表示没有行数限制) myLabel.numberOfLines = 2 // 设置标签的背景色 myLabel.backgroundColor = UIColor.white; // 设置标签的文本颜色 myLabel.textColor = UIColor.red; // 设置标签的字体和大小 myLabel.font = UIFont(name: "Helvetica",size: 20); // 设置对其方式 myLabel.textAlignment = .center; // 添加子视图 self.view.addSubview(myLabel); } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. // 设置视图背景色为灰色 self.view.backgroundColor = UIColor.lightGray; // 调用函数 showLabel(); }
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } ```
## 更新记录
1. 2015-12-22增加多行文本自适应高度 2. 2015-12-22Updated for Xcode 7.2 and Swift 2 3. 2017-11-21Updated for Xcode 9.1 and Swift 4
参考链接:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/index.html http://www.hangge.com/blog/cache/detail_528.html http://www.jianshu.com/p/ee6e4394d468 http://stackoverflow.com/questions/25180443/adjust-uilabel-height-to-text-swift
[END] (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|