Skip to content

Instantly share code, notes, and snippets.

@HarryGoodwin
Created November 10, 2019 10:28
Show Gist options
  • Save HarryGoodwin/f697e68c20f2afe18d37d5999b8c4fc4 to your computer and use it in GitHub Desktop.
Save HarryGoodwin/f697e68c20f2afe18d37d5999b8c4fc4 to your computer and use it in GitHub Desktop.
Simple bullet point UILabel rendering for iOS
import UIKit
import PlaygroundSupport
struct StringConstants {
static let bullet = "This is a long string, which should make the label wrap to multiple lines, showing us that the bullet point has rendered correctly with a sufficient indent on subsequent lines of text."
}
class MyViewController : UIViewController {
private let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupLabel()
let stringAttributes: [NSAttributedString.Key: Any] = [.font: label.font!]
let bulletString = makeBulletString(bullet: "▶︎ ",
content: StringConstants.bullet,
attributes: stringAttributes)
label.attributedText = bulletString
}
private func makeBulletString(bullet: String,
content: String,
attributes: [NSAttributedString.Key: Any]) -> NSAttributedString {
let fullString: String = "\(bullet)\(content)\n"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: fullString,
attributes: attributes)
let headerIndent = (bullet as NSString).size(withAttributes: attributes).width
attributedString.addAttributes([.paragraphStyle: makeParagraphStyle(headIndent: headerIndent)],
range: NSMakeRange(0, attributedString.length))
return attributedString
}
private func makeParagraphStyle(headIndent: CGFloat) -> NSParagraphStyle {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 0
paragraphStyle.headIndent = headIndent
return paragraphStyle
}
}
extension MyViewController {
private func setupLabel() {
view.addSubview(label)
label.numberOfLines = 0
label.font = UIFont.preferredFont(forTextStyle: .headline)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 10),
label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
])
}
}
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment