0

How can I resize NSScrollView using Swift?

class MainViewController: NSViewController {

    @IBOutlet weak var scrollView: NSScrollView!

    override func viewDidLoad {
        scrollView.setFrameOrigin(NSPoint(x: 340, y: 537))
        scrollView.setFrameSize(CGSize(width: scrollView.contentSize.width, height: 102.0))
    }

}

The above code works only if there are no constraints set. But, without constraints, the ScrollView doesn't stay in place when the window is resized.

curiously77
  • 225
  • 1
  • 4
  • 24

2 Answers2

1

If you are trying to set the document size (scrollable area) of a NSScrollView, then all we need to do is set the document view's size.

Note: This assumes there are no constraints on the document view.

scrollView.documentView?.setFrameSize(NSSize(width: 576, height: 56))

If you are trying to scroll to a specific region, see scrollToVisible(_:).

Chris Zielinski
  • 1,231
  • 1
  • 9
  • 11
  • Hey! I just updated my question, how can I include constrains and make it work the same time? I just need it to stay in place and auto resize when window is resized. The framesize is set to only change it's height. I want rest of it's attributes to auto resize. – curiously77 Sep 13 '19 at 18:51
  • I don’t understand. If you’re using constraints, then you can just use them to constrain the width to a constant value or to an aspect ratio with respect to the height, etc.. You can [programmatically add additional constraints](https://stackoverflow.com/a/26181982) too. – Chris Zielinski Sep 13 '19 at 19:37
  • So, I wanted to increase the height of the ScrollView towards the bottom without using any constraints. – curiously77 Sep 13 '19 at 19:39
  • Like an overscroll? – Chris Zielinski Sep 13 '19 at 19:41
  • Umm, I don't know what overscroll means but just increase the height towards the origin of the Y-axis. So had to reset the y-axis from the top of the screen and change the height. Anyway thanks for your help! – curiously77 Sep 13 '19 at 19:43
1

So this worked for me since my ScrollView was positioned on the top left:

scrollView.setFrameOrigin(NSPoint(x: self.view.frame.minX + 340, y: self.view.frame.maxY - 172))
scrollView.setFrameSize(CGSize(width: scrollView.contentSize.width, height: 102.0))

And the below image shows the settings used in Size Inspector to enable auto resize and also to stay to the top-left of the window.

ScrollView Size Inspector

curiously77
  • 225
  • 1
  • 4
  • 24