【问题标题】:Swift NSAttributedString add tableSwift NSAttributedString 添加表
【发布时间】:2018-05-20 07:41:31
【问题描述】:

我正在尝试以编程方式构建带有表的属性字符串。我发现如果我首先像这样创建 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。

【问题讨论】:

标签: swift macos swift4 nsattributedstring


【解决方案1】:

这是一个 Swift 4 代码 sn-p 就是这样做的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 2015-12-22
    相关资源
    最近更新 更多