ios开发 之 设置多种文字颜色/背景色/文字下划线/行间距

2016-10-27  本文已影响432人  清风沐沐

摘要: 一段文字中,有多种不同的文字颜色和背景色,可以用NSMutableAttributedString富文本来设置

NSMutableAttributedString常见的属性:

使用方法:

** 练练swift3.0 这里给一段swift代码**

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let label = UILabel(frame: CGRect(x: 30, y: (UIScreen.main.bounds.size.height - 100) / 2 - 100, width: UIScreen.main.bounds.size.width - 60, height: 100))
        label.backgroundColor = UIColor.blue
        label.numberOfLines = 0
        label.font = UIFont.systemFont(ofSize: 20)
        view.addSubview(label)
        
        let mutableAttributedString = NSMutableAttributedString(string: "人生若只如初见,何事西风悲画扇,等闲变却故人心,却道故人心易变")


        var dict = [NSForegroundColorAttributeName:UIColor.red,
                     NSFontAttributeName:UIFont.systemFont(ofSize: 13),
                     NSStrikethroughStyleAttributeName:"1"] as [String : Any]

        mutableAttributedString.setAttributes(dict, range: NSRange(location: 0, length: 16))

        dict = [NSBackgroundColorAttributeName:UIColor.green,
                NSUnderlineStyleAttributeName:1] as [String : Any]

        mutableAttributedString.setAttributes(dict, range: NSRange(location: 16, length: 8))

        mutableAttributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 30), range: NSRange(location: 24, length: 7))

        label.attributedText = mutableAttributedString
        
        
        let textView = UITextView(frame: CGRect(x: 30, y: (UIScreen.main.bounds.size.height - 100) / 2 + 100, width: UIScreen.main.bounds.size.width - 60, height: 100))
        textView.text = "最喜那一低头的温柔,恰似水莲花瓣的娇羞  --- 最喜那一低头的温柔,恰似水莲花瓣的娇羞   ---  最喜那一低头的温柔,恰似水莲花瓣的娇羞  ---  最喜那一低头的温柔,恰似水莲花瓣的娇羞   ---   最喜那一低头的温柔,恰似水莲花瓣的娇羞"
        textView.font = UIFont.systemFont(ofSize: 12)
        view.addSubview(textView)
        
        let mutableParagraphStyle = NSMutableParagraphStyle()
        mutableParagraphStyle.lineSpacing = 20
        
        dict = [NSFontAttributeName:UIFont.systemFont(ofSize: 16),
                NSParagraphStyleAttributeName: mutableParagraphStyle
                 ]
        
        textView.attributedText = NSAttributedString(string: textView.text, attributes: dict)
        
    }
上一篇 下一篇

猜你喜欢

热点阅读