Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hyuni/552e5fcd28d87d0f6ee4b28fa536cab2 to your computer and use it in GitHub Desktop.
Save hyuni/552e5fcd28d87d0f6ee4b28fa536cab2 to your computer and use it in GitHub Desktop.
Attributed string bullet points - Swift
//
// ViewController.swift
// BulletList
//
// Created by Harry Goodwin on 09/04/2016.
// Copyright © 2016 GG. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
var strings:[String] = []
@IBOutlet weak var bulletLabel: UILabel!
override func viewDidLoad()
{
super.viewDidLoad()
let nonBullet = "Hey this is a paragraph that shouldn't be formatted at all! It should not be indented in the slightest and hopefully be about three to four lines long! \n\n"
let bullet1 = "This is a small string"
let bullet2 = "This is more of medium string with a few more words etc."
let bullet3 = "Well this is certainly a longer string, with many more words than either of the previuos two strings"
strings = [bullet1, bullet2, bullet3]
let attributesDictionary = [NSFontAttributeName : bulletLabel.font]
let fullAttributedString = NSMutableAttributedString(string: nonBullet, attributes: attributesDictionary)
for string: String in strings
{
let bulletPoint: String = "\u{2022}"
let formattedString: String = "\(bulletPoint) \(string)\n"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: formattedString)
let paragraphStyle = createParagraphAttribute()
attributedString.addAttributes([NSParagraphStyleAttributeName: paragraphStyle], range: NSMakeRange(0, attributedString.length))
fullAttributedString.appendAttributedString(attributedString)
}
bulletLabel.attributedText = fullAttributedString
}
func createParagraphAttribute() ->NSParagraphStyle
{
var paragraphStyle: NSMutableParagraphStyle
paragraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.tabStops = [NSTextTab(textAlignment: .Left, location: 15, options: NSDictionary() as! [String : AnyObject])]
paragraphStyle.defaultTabInterval = 15
paragraphStyle.firstLineHeadIndent = 0
paragraphStyle.headIndent = 15
return paragraphStyle
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment