0

Like the title says, I am trying to dynamically add NSTextViews and NSImageViews to a NSStackView. First, I added a Scroll View using IB and that made a hierarchy of Bordered Scroll View -> Clip View -> Main View -> Stack View (Vertical). I want to be able to dynamically add views to the stack view and be able to scroll through them all. I used autolayout on the Bordered Scroll View.

The problem: I tested this by adding 100 NSTextViews and incrementing their y-positions to stack up on each other. But, I cannot scroll to the top. I have been trying to understand this for a couple days but I just cannot figure it out. I cannot scroll and see all the text views, but when I increase the window size I can see more of them. 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)
    }
}`
  • Okay so I figured out the problem was that I wasn't resizing my belowMainStackView. But now I have another problem. Everytime I resize a view, it grows upwards, but I need to grow downwards. Is there any way to do that? –  Jan 15 '17 at 21:32
  • See http://stackoverflow.com/a/38689333/3407091 – Taylor Jan 23 '17 at 20:48
  • @Taylor Thank you, but I solved it! –  Jan 25 '17 at 03:08

0 Answers0