Search code examples
objective-cmacoscocoaiboutletnsscrollview

NSScrollview not scrolling programmatically?


Note:Both Horizontal and vertical scrollers are visible on the screen and work fine.But I cant make them move Programatically.

I am working on a cocoa desktop application.I am using the NSScrollview in my Mainmenu.xib file and I am creating an outlet in its owner which is Appdelegate.h . Here is the outlet

@property(nonatomic,retain) IBOutlet NSScrollView* scrollview;

When I try to set a new referencing outlet of my NSScrollview from the interface builder and take the line to file's owner I only see one option "delegate".I dont see the outlet scrollview. So I connect the scrollview to the delegate in file's owner (As I cant see the scrollview outlet).

Now I am trying to do auto scrolling in my code.Here is the code

for(int a=0;a<10000;a++)
{
    NSPoint pointToScrollTo = NSMakePoint ( 100+a,100+a );  // Any point you like.
    [[self.scrollview contentView] scrollToPoint: pointToScrollTo];
    [self.scrollview reflectScrolledClipView: [self.scrollview contentView]];
}

This code does not work and The scroller does not scroll automatically.

I am trying to make a slow scrolling animation with this code.


Solution

  • NSClipView has a scrollToPoint: method which can be used to scroll programmatically:

    - (IBAction)scrollToMid:(id)sender
    {
        CGFloat midYPoint = [self.scrollView contentView].frame.size.height/2.0;
        [[self.scrollView contentView] scrollToPoint:NSMakePoint(0.0, midYPoint)];
        [self.scrollView reflectScrolledClipView:[self.scrollView contentView]];
    }
    

    If you want animated scrolling, you have to set the boundsOrigin via animator proxy. (Because neither NSScrollView nor NSClipView expose an animatable scroll point property)

    - (IBAction)scrollToMidAnimated:(id)sender
    {
        [NSAnimationContext beginGrouping];
        [[NSAnimationContext currentContext] setDuration:2.0];
        NSClipView* clipView = [self.scrollView contentView];
        NSPoint newOrigin = [clipView bounds].origin;
        newOrigin.y = [self.scrollView contentView].frame.size.height/2.0;
        [[clipView animator] setBoundsOrigin:newOrigin];
        [NSAnimationContext endGrouping];
    }