Swift NSAttributedString添加表

时间:2018-05-20 07:41:31

标签: swift swift4 nsattributedstring

我正在尝试以编程方式构建带有表的属性字符串。我发现如果我首先创建这样的HTML非常容易:

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>
"""

然后将其转换为:

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

但是如果我不想使用HTML怎么办?有没有办法以编程方式进行。可能与NSMutableAttributedString。

1 个答案:

答案 0 :(得分:0)

这是一个Swift 4代码片段,它就是这样做的:

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"))