Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func generateTableWithArray(array: [[String]], andTableStyle style: String?, forTableClassName tableClassName: String?, andRowClassNames rowClassNames: [String?]?, andCellClassNames cellClassNames: [[String?]?]?) -> String {
- var htmlString = ""
- htmlString += style == nil ? "" : "<style>\(style!)</style>\n"
- htmlString += tableClassName == nil ? "<table>\n" : "<table class=\"\(tableClassName!)\">\n"
- for row in array.enumerate() {
- if rowClassNames?.indices.contains(row.index) ?? false, let className = rowClassNames?[row.index] {
- htmlString += "<tr class=\"\(className)\">\n"
- } else {
- htmlString += "<tr>\n"
- }
- for coloumn in row.element.enumerate() {
- if cellClassNames?.indices.contains(row.index) ?? false && cellClassNames?[row.index]?.indices.contains(coloumn.index) ?? false,
- let classArray = cellClassNames?[row.index], let className = classArray[coloumn.index] {
- htmlString += "<td class=\"\(className)\">"
- } else {
- htmlString += "<td>"
- }
- htmlString += coloumn.element
- htmlString += "</td>\n"
- }
- htmlString += "</tr>\n"
- }
- return htmlString
- }
- //Example
- let tableData = [["<b>H1</b>", "H2", "H3", "H4"], ["R1", "R2", "R3", "R4"]]
- let tableStyle = ".tableClass {width: 100%; border-collapse: collapse; font-family: Helvetica; font-size: 13px}" +
- ".headingClass td {border-bottom: 1px solid gray;}" +
- ".cellClass {font-family: monospace}"
- let htmlTable = generateTableWithArray(tableData, andTableStyle: tableStyle, forTableClassName: "tableClass", andRowClassNames: ["headingClass", nil], andCellClassNames: [nil, ["cellClass", nil, "cellClass", nil]])
- //Attributed String from table. Good for previewing the table in a playground
- var attributedTableString = try! NSAttributedString(
- data: htmlTable.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
- options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
- documentAttributes: nil)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement