Skip to content

Instantly share code, notes, and snippets.

@sfsam
Created March 21, 2013 20:02
Show Gist options
  • Save sfsam/5216214 to your computer and use it in GitHub Desktop.
Save sfsam/5216214 to your computer and use it in GitHub Desktop.
MOWTextField is an NSTextField subclass which lets you specify an alternate short string. The short string will be used if the frame is too short for the normal string value.
//
// MOWTextField.h
//
//
// Created by Sanjay Madan on 03/21/13.
// Copyright (c) 2013 mowglii.com. All rights reserved.
//
#import <Cocoa/Cocoa.h>
// MOWTextField
//
// You can set a short string value on MOWTextField.
// When the frame becomes too short to fit the
// original string, the short string will be swapped
// in. If the frame becomes too short for the short
// string, the default linebreak behavior (clip,
// truncate, etc) will kick in.
@interface MOWTextField : NSTextField
- (void)setShortStringValue:(NSString *)aShortStringValue;
- (NSString *)shortStringValue;
@end
// MOWTextFieldCell
//
// The actual functionality of MOWTextField is
// implemented by MOWTextFieldCell.
@interface MOWTextFieldCell : NSTextFieldCell
@property (nonatomic, copy) NSString *shortStringValue;
@end
//
// MOWTextField.m
//
//
// Created by Sanjay Madan on 03/21/13.
// Copyright (c) 2013 mowglii.com. All rights reserved.
//
#import "MOWTextField.h"
// MOWTextField
@implementation MOWTextField
+ (Class)cellClass
{
return [MOWTextFieldCell class];
}
- (void)setShortStringValue:(NSString *)aShortStringValue
{
[[self cell] setShortStringValue:aShortStringValue];
}
- (NSString *)shortStringValue
{
return [[self cell] shortStringValue];
}
@end
// MOWTextFieldCell
@implementation MOWTextFieldCell
- (NSString *)shortStringValue
{
// If user has not set a short string value, just
// return [self stringValue] so we behave like a
// normal NSTextField.
if (_shortStringValue == nil) {
return [self stringValue];
}
return _shortStringValue;
}
- (NSAttributedString *)attributedShortStringValue
{
NSAttributedString *attrStr = [self attributedStringValue];
NSDictionary *attrs = [attrStr attributesAtIndex:0 effectiveRange:NULL];
return [[NSAttributedString alloc] initWithString:self.shortStringValue attributes:attrs];
}
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
// When getting titleRect, inset the bounds by 2px horizontally
// because that seems to be what NSTextFieldCell does.
NSRect titleRect = [self titleRectForBounds:NSInsetRect(cellFrame, 2.f, 0.f)];
CGFloat stringWidth = [[self attributedStringValue] size].width;
if (NSWidth(titleRect) < stringWidth) {
[[self attributedShortStringValue] drawInRect:titleRect];
}
else {
[super drawInteriorWithFrame:cellFrame inView:controlView];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment