LoginSignup
5
5

More than 5 years have passed since last update.

NSScrollViewの内容センタリング

Last updated at Posted at 2013-12-19

なんか、ネットで探すと色々皆さん工夫して色々書いてるんだけど、煎じ詰めるとこれだけで良い気がする。

constrainBoundsRect: は OS X 10.9 からなので、それ以前に対応する場合は deprecated な constrainScrollPoint: をオーバーライドすれば良い。

MyCenteringClipView.h
#import <Cocoa/Cocoa.h>

@interface MyCenteringClipView : NSClipView
@end
MyCenteringClipView.m
#import "MyCenteringClipView.h"

@implementation MyCenteringClipView

- (NSRect)constrainBoundsRect:(NSRect)proposedBounds
{
    NSRect documentBounds = [[self documentView] bounds];
    NSPoint delta         = NSMakePoint(NSWidth(documentBounds)  - NSWidth(proposedBounds),
                                        NSHeight(documentBounds) - NSHeight(proposedBounds));

    CGFloat x = (delta.x < 0) ? (delta.x / 2) : MAX(0, MIN(proposedBounds.origin.x, delta.x));
    CGFloat y = (delta.y < 0) ? (delta.y / 2) : MAX(0, MIN(proposedBounds.origin.y, delta.y));
    proposedBounds.origin = NSMakePoint(floor(x), floor(y));

    return proposedBounds;
}

@end

ちな、documentViewは intrinsicContentSize で自分のサイズを返すようにしてます。

手元で試してる限りでは、これだけでちゃんと動いてる。

5
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5