Skip to content

Instantly share code, notes, and snippets.

@bob910078
Created July 9, 2019 06:55
Show Gist options
  • Save bob910078/6dc50095633a968c42b42707a7acddfc to your computer and use it in GitHub Desktop.
Save bob910078/6dc50095633a968c42b42707a7acddfc to your computer and use it in GitHub Desktop.
//
// ViewController.swift
// Font
//
// Created by Bob on 2019/7/9.
// Copyright © 2019 Hamster. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tv: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let attr = NSAttributedString()
tv.attributedText = attr.appendLine(text: "Somebody said:")
.appendBullet(text: "An apple a day")
.appendBullet(text: "Keep doctor away")
}
}
extension NSAttributedString {
@discardableResult
func appendBullet(text: String, bulletSymbol: String = "\u{2022}", bulletColor: UIColor = .black) -> NSAttributedString {
let font = UIFont.systemFont(ofSize: 30)
let indentation: CGFloat = 20
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.tabStops = [ NSTextTab(textAlignment: .left, location: indentation) ]
paragraphStyle.defaultTabInterval = indentation
paragraphStyle.headIndent = indentation
let bulletText = "\(bulletSymbol)\t" + "\(text)\n"
let bulletStyleModifier: [NSAttributedString.Key:Any] = [.font: font, .paragraphStyle: paragraphStyle]
let tmp = NSMutableAttributedString(attributedString: self)
tmp.append(NSAttributedString(string: bulletText))
tmp.addAttributes([.foregroundColor: bulletColor], range: NSRange(location: self.length, length: bulletSymbol.count))
tmp.addAttributes(bulletStyleModifier, range: NSRange(location: self.length, length: bulletText.count))
return tmp
}
@discardableResult
func appendLine(text: String, color: UIColor = .red) -> NSAttributedString {
let font = UIFont.systemFont(ofSize: 30)
let modifier: [NSAttributedString.Key:Any] = [.font: font, .foregroundColor: color]
let willAppendString = text + "\n"
let tmp = NSMutableAttributedString(attributedString: self)
tmp.append(NSAttributedString(string: willAppendString))
tmp.addAttributes(modifier, range: NSRange(location: self.length, length: text.count))
return tmp
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment