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

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


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.
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值