创建Label
let rect = CGRectMake(10, 100, 320, 100) let label : UILabel = UILabel (frame: rect) self.view.addSubview(label)
Label常用属性
label.backgroundColor = UIColor.orangeColor()//背景颜色 label.text = "this is a Label"//内容 label.font = UIFont.boldSystemFontOfSize(20)//字号 label.textColor = UIColor.whiteColor()//字体颜色 label.textAlignment = NSTextAlignment.Center//内容显示位置 label.lineBreakMode = NSLineBreakMode.ByCharWrapping//内容截断方式 label.numberOfLines = 0//内容显示的行数 label.highlighted = true//高亮状态 label.highlightedTextColor = UIColor.greenColor()//高亮时文字颜色 label.shadowColor = UIColor.blackColor()//阴影颜色 label.shadowOffset = CGSize.init( 1, height: 1)//阴影位置 label.adjustsFontSizeToFitWidth = true//自适应改变文字大小
layer属性
label.layer.masksToBounds = true//掩藏超出部分 label.layer.cornerRadius = 10//圆角 label.layer.borderWidth = 2//边框 label.layer.borderColor = UIColor.greenColor().CGColor//边框颜色 label.transform = CGAffineTransformMakeRotation(0.3)//旋转
富文本设置
let attributeString = NSMutableAttributedString(string: "hello world") attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 16)!, range: NSMakeRange(0,6))//设置字体 attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: NSMakeRange(0, 3))//设置字体颜色 attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(2, 2))//设置字体背景颜色 let url = NSURL(string: "http://www.baidu.com") attributeString.addAttribute(NSLinkAttributeName, value:url! , range: NSMakeRange(0, 11))//链接属性点击将启动浏览器打开一个URL地址,中间用到一个代理函数,UILabel 和 UITextField 无法使用该属性 UITextView可用 label.attributedText = attributeString
添加点击事件
let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "Click:") label.userInteractionEnabled = true label.tag = 101 label.addGestureRecognizer(tap)
func Click(let tap : UITapGestureRecognizer){ let Label = self.view.viewWithTag((tap.view?.tag)!) as! UILabel print(Label.text!) }
显示HTML标签 富文本设置
let html = "this is html <a href="http://www.baidu.com">link</a>" let data = html.dataUsingEncoding(NSUTF32StringEncoding, allowLossyConversion: false) let textAttr = try! NSAttributedString(data: data!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil) label.multipleTouchEnabled = true label.attributedText = textAttr