Created
December 4, 2010 00:46
-
-
Save eventualbuddha/727781 to your computer and use it in GitHub Desktop.
Adds a sizeToFit method to CPViews that will resize a view to fit its subviews.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import <AppKit/CPView.j> | |
@implementation CPView (sizeToFit) | |
- (void)sizeToFit | |
{ | |
[self sizeToFitWithInset:[self hasThemeAttribute:@"content-inset"] && [self currentValueForThemeAttribute:@"content-inset"] || CGInsetMakeZero()]; | |
} | |
- (void)sizeToFitWithInset:(CGInset)inset | |
{ | |
var result = CGSizeMake(inset.left, inset.top), | |
rect = {origin: CGPointMakeZero(), size: result}, | |
roomForAnchoredSubviews = CGSizeMakeZero(); | |
for (var i = 0, count = [_subviews count]; i < count; i++) | |
{ | |
var subview = _subviews[i], | |
autoresizingMask = [subview autoresizingMask]; | |
if (autoresizingMask & CPViewMinYMargin) | |
{ | |
// bottom-anchored view | |
var overlap = CGRectIntersection(rect, [subview frame]); | |
if (!CGRectIsEmpty(overlap)) | |
roomForAnchoredSubviews.height += CGRectGetHeight(overlap); | |
} | |
else if (autoresizingMask & CPViewMinXMargin) | |
{ | |
// right-anchored view | |
var overlap = CGRectIntersection(rect, [subview frame]); | |
if (!CGRectIsEmpty(overlap)) | |
roomForAnchoredSubviews.width += CGRectGetWidth(overlap); | |
} | |
else | |
{ | |
var frame = [subview frame], | |
maxX = CGRectGetMaxX(frame), | |
maxY = CGRectGetMaxY(frame); | |
if (result.width < maxX) | |
result.width = maxX; | |
if (result.height < maxY) | |
result.height = maxY; | |
} | |
[self setFrameSize:CGSizeMake(result.width + roomForAnchoredSubviews.width, result.height + roomForAnchoredSubviews.height)]; | |
} | |
result.width += roomForAnchoredSubviews.width + inset.right; | |
result.height += roomForAnchoredSubviews.height + inset.bottom; | |
[self setFrameSize:result]; | |
} | |
- (BOOL)hasThemeAttribute:(CPString)attributeName | |
{ | |
return !![[self _themeAttributeDictionary] objectForKey:attributeName]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment