Advertisement
Guest User

Untitled

a guest
May 24th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. func generateTableWithArray(array: [[String]], andTableStyle style: String?, forTableClassName tableClassName: String?, andRowClassNames rowClassNames: [String?]?, andCellClassNames cellClassNames: [[String?]?]?) -> String {
  2. var htmlString = ""
  3.  
  4. htmlString += style == nil ? "" : "<style>\(style!)</style>\n"
  5. htmlString += tableClassName == nil ? "<table>\n" : "<table class=\"\(tableClassName!)\">\n"
  6.  
  7. for row in array.enumerate() {
  8.  
  9. if rowClassNames?.indices.contains(row.index) ?? false, let className = rowClassNames?[row.index] {
  10. htmlString += "<tr class=\"\(className)\">\n"
  11. } else {
  12. htmlString += "<tr>\n"
  13. }
  14.  
  15. for coloumn in row.element.enumerate() {
  16.  
  17. if cellClassNames?.indices.contains(row.index) ?? false && cellClassNames?[row.index]?.indices.contains(coloumn.index) ?? false,
  18. let classArray = cellClassNames?[row.index], let className = classArray[coloumn.index] {
  19. htmlString += "<td class=\"\(className)\">"
  20. } else {
  21. htmlString += "<td>"
  22. }
  23.  
  24. htmlString += coloumn.element
  25. htmlString += "</td>\n"
  26. }
  27. htmlString += "</tr>\n"
  28. }
  29.  
  30. return htmlString
  31. }
  32.  
  33. //Example
  34.  
  35. let tableData = [["<b>H1</b>", "H2", "H3", "H4"], ["R1", "R2", "R3", "R4"]]
  36. let tableStyle = ".tableClass {width: 100%; border-collapse: collapse; font-family: Helvetica; font-size: 13px}" +
  37. ".headingClass td {border-bottom: 1px solid gray;}" +
  38. ".cellClass {font-family: monospace}"
  39.  
  40. let htmlTable = generateTableWithArray(tableData, andTableStyle: tableStyle, forTableClassName: "tableClass", andRowClassNames: ["headingClass", nil], andCellClassNames: [nil, ["cellClass", nil, "cellClass", nil]])
  41.  
  42. //Attributed String from table. Good for previewing the table in a playground
  43.  
  44. var attributedTableString = try! NSAttributedString(
  45. data: htmlTable.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
  46. options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
  47. documentAttributes: nil)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement