alagris
alagris

Reputation: 2206

Swift NSAttributedString add table

I am trying to programmatically build attributed string with table in it. I figured out it's very easy if I first create HTML like this:

let html =
"""
<table style="height: 51px;" width="147">
<tbody>
<tr>
<td style="width: 65.5px;">a</td>
<td style="width: 65.5px;">b</td>
</tr>
<tr>
<td style="width: 65.5px;">c</td>
<td style="width: 65.5px;">d</td>
</tr>
</tbody>
</table>
"""

and then convert it like this:

var str = NSAttributedString(html: html.data(using: .utf8)!,    options: [:], documentAttributes: nil)!

But what if I don't want to use HTML? Is there a way to just do it programmatically. Probably with NSMutableAttributedString.

Upvotes: 2

Views: 2796

Answers (1)

alagris
alagris

Reputation: 2206

Here is a Swift 4 code snippet that does just that:

var table = NSTextTable()
table.numberOfColumns = 2

func makeCell(row: Int, column: Int, text: String) -> NSMutableAttributedString {
    let textBlock = NSTextTableBlock(table: table, startingRow: row, rowSpan: 1, startingColumn: column, columnSpan: 1)

    textBlock.setWidth(4.0, type: NSTextBlock.ValueType.absoluteValueType, for: NSTextBlock.Layer.border)
    textBlock.setBorderColor(.blue)

    let paragraph = NSMutableParagraphStyle()
    paragraph.textBlocks = [textBlock]

    let cell = NSMutableAttributedString(string: text + "\n", attributes: [.paragraphStyle: paragraph])

    return cell
}

let content = NSMutableAttributedString("some text")
content.append(NSAttributedString(string: "\n")) // this newline is required in case content is not empty. 

//If you append table cells to some text without newline, the first row might not show properly.
content.append(makeCell(row: 0, col: 0, text: "c00"))
content.append(makeCell(row: 0, col: 1, text: "c 0 1"))
content.append(makeCell(row: 1, col: 0, text: "c 1 0"))
content.append(makeCell(row: 1, col: 1, text: "c11"))

Upvotes: 3

Related Questions