您的位置:首页 > Web前端 > CSS

如何改变Label中字符串的样式

2016-01-06 19:42 751 查看
可设置的属性包括:字体,大小,行距,缩进,下划线…… 你能想到的都有。本例子只列举了几个简单的属性,起抛砖引玉的作用!请直接看代码:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let outputString = "滚滚长江东逝水,浪花淘尽英雄。是非成败转头空。青山依旧在,几度夕阳红。白发渔樵江渚上,惯看秋月春风。一壶浊酒喜相逢。古今多少事,都付笑谈中。"

let label = UILabel(frame: CGRectMake(0,100,view.bounds.size.width, 120))

label.attributedText = setLabelStyle(outputString)
label.numberOfLines = 0

view.addSubview(label)

}

func setLabelStyle(labelStr:String) -> NSAttributedString{
//字体名称和大小
let contentFont = UIFont(name: "Copperplate", size: 20)

//阴影设置
let shadow:NSShadow = NSShadow()
shadow.shadowOffset = CGSizeMake(-2.0, -2.0)

//属性数组 大约有20个
let attributes:[String:AnyObject]? = [
NSFontAttributeName: contentFont!, //设置字体
NSUnderlineStyleAttributeName: 1, //0 没有下划线,1有下划线
NSForegroundColorAttributeName: UIColor.redColor(), //字符串的颜色
NSTextEffectAttributeName: NSTextEffectLetterpressStyle,
NSShadowAttributeName:shadow,
NSStrokeWidthAttributeName: 3.0,
]

// 行距
let lineStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
lineStyle.lineSpacing = 10
lineStyle.headIndent = 0 //缩进
lineStyle.firstLineHeadIndent = 30 //首行缩进

let contentStr = NSMutableAttributedString(string: labelStr)

contentStr.addAttributes(attributes!, range: NSRange(location: 5, length: 12))
contentStr.addAttribute(NSParagraphStyleAttributeName, value: lineStyle, range: NSRange(location: 0, length: labelStr.characters.count))

return contentStr

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: