Skip to content

Instantly share code, notes, and snippets.

@Thesaurus
Created September 16, 2015 12:13
Show Gist options
  • Save Thesaurus/37cb05a212b65c32cda6 to your computer and use it in GitHub Desktop.
Save Thesaurus/37cb05a212b65c32cda6 to your computer and use it in GitHub Desktop.
NSButton checkbox with wrapping title (despite what IB says a check box title does not wrap)
#import <Cocoa/Cocoa.h>
@interface BPCheckBoxButton : NSButton
@end
@implementation BPCheckBoxButton
- (void)setTitle:(NSString *)aString
{
/*
Check box title does not wrap by default, despite what IB says.
*/
CGFloat imageWidth = self.image.size.width;
// rough estimate. more exact metrics may be available.
CGFloat maxWidth = self.frame.size.width - imageWidth * 1.5;
aString = [aString bp_wrapStringMaxWidth:maxWidth forFont:self.font];
[super setTitle:aString];
}
@end
@interface NSString (CheckBox)
- (NSArray *)bp_splitStringMaxWidth:(CGFloat)width font:(NSFont *)font;
- (NSString *)bp_wrapStringMaxWidth:(CGFloat)width forFont:(NSFont *)font;
@end
@implementation NSString (CheckBox)
- (NSArray *)bp_splitStringMaxWidth:(CGFloat)width font:(NSFont *)font
{
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
NSArray *wordArray = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *line = @"";
NSString *lineWithNext = @"";
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
for (NSUInteger i = 0; i < [wordArray count]; i++) {
if (line.length == 0) { line = [wordArray objectAtIndex:i]; }
if (i+1 < [wordArray count]) {
lineWithNext = [[NSArray arrayWithObjects:line, [wordArray objectAtIndex:i+1], nil] componentsJoinedByString:@" "];
if (((int)[lineWithNext sizeWithAttributes:attributes].width) <= width) {
line = lineWithNext;
} else {
[tempArray addObject:line];
line = @"";
}
} else {
[tempArray addObject:line];
}
}
return tempArray;
}
- (NSString *)bp_wrapStringMaxWidth:(CGFloat)width forFont:(NSFont *)font
{
NSArray *components = [self bp_splitStringMaxWidth:width font:font];
NSString *wrappedString = [components componentsJoinedByString:@"\n"];
return wrappedString;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment