創建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"http://內容 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(width: 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
新聞熱點
疑難解答