Home > Net >  macOS NSScrollView Not Scrolling Vertically
macOS NSScrollView Not Scrolling Vertically

Time:12-17

I am trying to add few views to see if the NSScrollView will scroll vertically but it is not doing anything.

  private func configure2() {
        
        var yOffset = 0
        
        let scrollView = NSScrollView(frame: NSRect(x: 0, y: 0, width: 400, height: 900))
        
        scrollView.hasVerticalScroller = true
        
        for _ in 1...20 {
            
            let v = NSView(frame: NSRect(x: 0, y: 0   yOffset, width: 50, height: 20))
            v.wantsLayer = true
            v.layer?.backgroundColor = NSColor.red.cgColor
            
            scrollView.addSubview(v)
            yOffset  = 40
        }
        
        scrollView.backgroundColor = NSColor.green
        
        self.addSubview(scrollView)
        
    }

enter image description here

I remember in UIKit I can set the contentSize property of UIScrollView but in macOS I cannot set contentSize.

CodePudding user response:

You need to set either the documentView or contentView of your NSScrollView. Then, you'll add your subviews to that view.

private func configure2() {
    var yOffset = 0
    let scrollView = NSScrollView(frame: NSRect(x: 0, y: 0, width: 400, height: 900))
    let documentView = NSView(frame: .zero)
    scrollView.hasVerticalScroller = true
    for _ in 1...20 {
        
        let v = NSView(frame: NSRect(x: 0, y: 0   yOffset, width: 50, height: 20))
        v.wantsLayer = true
        v.layer?.backgroundColor = NSColor.red.cgColor
        
        documentView.addSubview(v)
        yOffset  = 40
    }
    print(yOffset)
    documentView.frame = .init(x: 0, y: 0, width: 400, height: yOffset)
    scrollView.documentView = documentView
    scrollView.backgroundColor = NSColor.green
    self.addSubview(scrollView)
}
  • Related