싱크로나이즈드 스크롤 구현하기

여러개의 NSScrollView를 사용할때 스크롤뷰들 중에서 하나만 스크롤해도 여러개의 스크롤 뷰가 동시에 따라 움지이는 싱크로나이즈드 스크롤(Synchronized scroll)을 구현하기 위한 방법을 소개한다.

스크롤 이벤트 감지

NSScrollView의 스크롤이벤트를 받아오기 위해서는 NSScrollView가 가진 contentView의 바운드가 변하는 것을 모니터링 하면된다. 다음 코드로 스크롤뷰가 가진 contentView의 bound변화 notification을 활성화 한 후

[[scrollView contentView] setPostsBoundsChangedNotifications:YES];

노티피케이션센터에 NSViewBoundsDidChangeNotification에대한 옵저버를 등록하여 이벤트를 받아온다.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentDidScroll:) name:NSViewBoundsDidChangeNotification object:contentView];

NSScrollView를 특정 포인트로 스크롤 하기

앞에서 viewBound의 변화에대한 노티피케이션을 받았을때 변화된 bound를 불러와서 다른 스크롤뷰를 강제로 스크롤 시키면 된다.

- (void)contentDidScroll:(NSNotification*)notification_ {

    NSClipView* scrolledView = (NSClipView*)[notification_ object];
    scrolledView.bounds.origin;


    // 아래 두 코드중 하나 이용 가능
    [[scrollView contentView] scrollToPoint:scrolledView.origin];
    [[scrollView documentView] scrollPoint:scrolledView.origin];
}