Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-10-01

Creating a scrollview programatically in Swift

In the previous post about scrollviews I still used the interface builder to create the scrollview. While that worked I still had problems getting it to scroll right. For some reason the scrollview would at times auto-scroll to the upper-left corner. And as so often, I do not have the time to spend more time on this problem. So I decided to try an alternative solution in which I create the scrollview and the document view programatically. Sadly, there are little or no examples out on this, so I had to experiment just a little. This is what I came up with:

class MyDocumentWindowController: NSWindowController {
    
    
    override func windowDidLoad() {
        
        
        // Create scrollview
        
        let scrollView = NSScrollView(frame: window!.contentView!.frame)
        
        scrollView.hasHorizontalScroller = true
        scrollView.hasVerticalScroller = true
        scrollView.autohidesScrollers = true
        scrollView.borderType = NSBorderType.NoBorder
        scrollView.autoresizingMask = NSAutoresizingMaskOptions(arrayLiteral: .ViewWidthSizable, .ViewHeightSizable)
        
        
        // Create document view
        
        let docView = LineView()
        docView.autoresizingMask = NSAutoresizingMaskOptions(arrayLiteral: .ViewWidthSizable, .ViewHeightSizable)
        
        
        // Add the docView to the scrollView
        
        scrollView.documentView = docView
        
        
        // Add the document to the docView (note: This will trigger an update of its frame based on the available and needed size, hence it must be done after the docView is inserted into the scrollview)
        
        docView.document = document as? MyDocument
        
        
        // Set the scrollview as the window's main view
        
        window!.contentView = scrollView
    }

}

In the didSet method of docView I update the frame as detailed in the previous post on this subject. That is why it needs to be set after the docView is added to the scrollView.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment