Skip to content

Instantly share code, notes, and snippets.

@bjhomer
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjhomer/b4fae0a13cd731988b34 to your computer and use it in GitHub Desktop.
Save bjhomer/b4fae0a13cd731988b34 to your computer and use it in GitHub Desktop.
//
// DOXLabelWrapper.m
// Autolayout
//
// Created by BJ Homer on 7/11/14.
// Copyright (c) 2014 BJ Homer. All rights reserved.
//
#import "DOXLabelWrapper.h"
@interface DOXLabelWrapper()
@property (nonatomic) NSColor *color;
@property (nonatomic) CGFloat cornerRadius;
@property (nonatomic) NSTextField *titleField;
@end
@implementation DOXLabelWrapper
// In my test case, frame.size = {width: 163, height: 40}
- (instancetype)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.color = [NSColor blueColor];
self.cornerRadius = 8;
CGRect textRect = CGRectInset(self.bounds, self.cornerRadius, self.cornerRadius);
NSTextField *titleField = [[NSTextField alloc] initWithFrame:textRect];
titleField.drawsBackground = false;
titleField.editable = false;
titleField.bezeled = false;
titleField.bordered = false;
titleField.stringValue = @"This is a string";
titleField.textColor = [NSColor whiteColor];
self.titleField = titleField;
/// Setting this flag to YES causes the view to have no visible size.
BOOL useAutoresizingMask = NO;
if (useAutoresizingMask) {
titleField.translatesAutoresizingMaskIntoConstraints = YES;
titleField.autoresizingMask = (NSViewWidthSizable | NSViewHeightSizable);
[self addSubview:titleField];
}
else {
[self addSubview:titleField];
titleField.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *views = NSDictionaryOfVariableBindings(titleField);
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-(8)-[titleField]-(8)-|"
options:0 metrics:0 views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(8)-[titleField]-(8)-|"
options:0 metrics:0 views:views]];
}
self.wantsLayer = YES;
}
return self;
}
- (BOOL)wantsUpdateLayer
{
return YES;
}
- (void)updateLayer
{
self.layer.backgroundColor = self.color.CGColor;
self.layer.cornerRadius = self.cornerRadius;
}
@end
@bjhomer
Copy link
Author

bjhomer commented Jul 11, 2014

If useAutoresizingMask is YES, then the titleField shrinks down to height == 0, width == 4. This happens even though the titleField's -fittingSize is much larger than that.

Shouldn't the two code paths be equivalent?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment