2020-09-20 13:46:54 +02:00
|
|
|
//
|
|
|
|
|
// UICodeHighlightingLabel.swift
|
|
|
|
|
// pass
|
|
|
|
|
//
|
|
|
|
|
// Created by Danny Moesch on 20.01.19.
|
|
|
|
|
// Copyright © 2019 Bob Sun. All rights reserved.
|
|
|
|
|
//
|
2019-01-20 11:24:57 +01:00
|
|
|
|
|
|
|
|
import passKit
|
2020-06-28 21:25:40 +02:00
|
|
|
import UIKit
|
2019-01-20 11:24:57 +01:00
|
|
|
|
|
|
|
|
class UICodeHighlightingLabel: UILocalizedLabel {
|
|
|
|
|
private static let CODE_ATTRIBUTES: [NSAttributedString.Key: Any] = [.font: UIFont(name: "Menlo-Regular", size: 12)!]
|
|
|
|
|
private static let ATTRIBUTED_NEWLINE = NSAttributedString(string: "\n")
|
|
|
|
|
|
|
|
|
|
override func awakeFromNib() {
|
|
|
|
|
super.awakeFromNib()
|
|
|
|
|
guard let text = text else {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
attributedText = formatCode(in: text)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Format code sections in a multiline string block.
|
|
|
|
|
///
|
|
|
|
|
/// A line in the string is interpreted as a code section if it starts with two spaces.
|
|
|
|
|
///
|
|
|
|
|
/// - Parameter text: Multiline string block
|
|
|
|
|
/// - Returns: Same multiline string block with code sections formatted
|
|
|
|
|
private func formatCode(in text: String) -> NSMutableAttributedString {
|
2020-01-18 22:30:38 +01:00
|
|
|
let formattedText = text.splitByNewline()
|
|
|
|
|
.map { line -> NSAttributedString in
|
2019-01-20 11:24:57 +01:00
|
|
|
if line.starts(with: " ") {
|
2020-01-18 22:30:38 +01:00
|
|
|
return NSAttributedString(string: line, attributes: UICodeHighlightingLabel.CODE_ATTRIBUTES)
|
2019-01-20 11:24:57 +01:00
|
|
|
}
|
2020-01-18 22:30:38 +01:00
|
|
|
return NSAttributedString(string: line)
|
2020-07-05 00:20:08 +02:00
|
|
|
}
|
|
|
|
|
.reduce(into: NSMutableAttributedString(string: "")) {
|
2019-01-20 11:24:57 +01:00
|
|
|
$0.append($1)
|
|
|
|
|
$0.append(UICodeHighlightingLabel.ATTRIBUTED_NEWLINE)
|
|
|
|
|
}
|
|
|
|
|
formattedText.deleteCharacters(in: NSRange(location: formattedText.length - 1, length: 1))
|
|
|
|
|
return formattedText
|
|
|
|
|
}
|
|
|
|
|
}
|