其他内容呢?喜欢表格上方/下方的文字?收缩?保持与桌子相同的最小宽度?我的假设与表格的宽度相同。
以下示例不是完整的答案,请将其视为您必须开始的概念验证。
屏幕录制
对于 GIF 质量很抱歉,但限制为 2MB。
示例项目
- 在 IB 中添加了 Text View 并将其连接到插座
- 其余在代码中完成
重要部分
滚动条
同时设置它们并让它们根据内容自动隐藏。
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = true
scrollView.autohidesScrollers = true
切换文本视图调整大小和设置容器大小
由于viewDidLayout 覆盖等原因,这是一个蹩脚的实现。例如 - 如果您的鼠标和窗口大小调整速度足够快,则最终的尺寸可能远小于 300,等等。
这里的重要部分是我要更改哪些属性,并且在达到阈值时我坚持固定的containerSize(水平)。
if textView.bounds.size.width > 300 {
textView.isHorizontallyResizable = false
textView.textContainer?.widthTracksTextView = true
} else {
textView.textContainer?.widthTracksTextView = false
textView.isHorizontallyResizable = true
textView.textContainer?.containerSize = NSSize(width: textView.bounds.size.width, height: CGFloat.greatestFiniteMagnitude)
}
完整代码
import Cocoa
class ViewController: NSViewController {
@IBOutlet var scrollView: NSScrollView!
@IBOutlet var textView: NSTextView!
let loremIpsum = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\n"
let loremIpsumCell = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n"
override func viewDidLayout() {
super.viewDidLayout()
if textView.bounds.size.width > 300 {
textView.isHorizontallyResizable = false
textView.textContainer?.widthTracksTextView = true
} else {
textView.textContainer?.widthTracksTextView = false
textView.isHorizontallyResizable = true
textView.textContainer?.containerSize = NSSize(width: textView.bounds.size.width, height: CGFloat.greatestFiniteMagnitude)
}
}
override func viewDidLoad() {
super.viewDidLoad()
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = true
scrollView.autohidesScrollers = true
let content = NSMutableAttributedString(string: loremIpsum)
let table = NSTextTable()
table.numberOfColumns = 2
table.setContentWidth(100, type: .percentageValueType)
(0...1).forEach { row in
(0...5).forEach { column in
let block = NSTextTableBlock(table: table, startingRow: row, rowSpan: 1, startingColumn: column, columnSpan: 1)
block.setWidth(1.0, type: .absoluteValueType, for: .border)
block.setBorderColor(.orange)
let paragraph = NSMutableParagraphStyle()
paragraph.textBlocks = [block]
let cell = NSMutableAttributedString(string: loremIpsumCell, attributes: [.paragraphStyle: paragraph])
content.append(cell)
}
}
content.append(NSAttributedString(string: loremIpsum))
textView.textStorage?.setAttributedString(content)
}
}