就像标题所说,我试图动态地将NSTextViews和NSImageViews添加到NSStackView。首先,我使用IB添加了一个Scroll View,并创建了一个Bordered Scroll View层次结构 - >剪辑视图 - >主视图 - >堆栈视图(垂直)。我希望能够动态地向堆栈视图添加视图,并能够全部滚动它们。我在Bordered Scroll View上使用了autolayout。
问题:我通过添加100个NSTextViews并递增它们的y位置以相互堆叠来测试它。但是,我无法滚动到顶部。我一直试图理解这几天,但我无法理解。我无法滚动并查看所有文本视图,但是当我增加窗口大小时,我可以看到更多它们。 TIA! `
import Cocoa
class ViewController: NSViewController {
var xLoc = CGFloat(0)
var yLoc = CGFloat(0)
@IBOutlet weak var mainView: NSStackView!
@IBOutlet weak var belowMainView: NSStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
for index in 1...100 {
var txt = "Num: \(index)"
setup(text: txt)
}
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func setup(text: String){
let tempTextView = NSTextView(frame: NSMakeRect(xLoc, yLoc, 320, 10))
tempTextView.append(text)
tempTextView.isEditable = false
tempTextView.translatesAutoresizingMaskIntoConstraints = false
// mainView.addSubview(tempTextView)
belowMainView.addSubview(tempTextView)
yLoc += 20
}
}
// Adding an append function to textView functionality
extension NSTextView {
func append(_ string: String) {
self.textStorage?.append(NSAttributedString(string: string))
// Scrolls to end of document if it is out of view
self.scrollToEndOfDocument(nil)
}
}`