Skip to content

Instantly share code, notes, and snippets.

@marteinn
Last active April 26, 2021 04:36
Show Gist options
  • Save marteinn/fa9301ad349b755da2e6 to your computer and use it in GitHub Desktop.
Save marteinn/fa9301ad349b755da2e6 to your computer and use it in GitHub Desktop.
NSButton example: Vertical aligning text in a NSButton

Vertical aligning text in NSButton

This is a example on how you can top align text in a NSButton using a custom cell class.

Implementation

#import "MSButtonTextTopCell.h"

MSButtonTextTopCell *cell = [[MSButtonTextTopCell alloc] init];
NSButton *button = [[NSButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100];
[button setCell:cell];
[button setTitle:@"Button Text"];

[self addSubview:button];
//
// MSButtonTextTopCell.h
// <Project>
//
// Created by Martin Sandström on 2015-09-23.
// Copyright (c) 2015 Martin Sandström. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface MSButtonTextTopCell : NSButtonCell
@end
//
// MSButtonTextTopCell.m
// <Project>
//
// Created by Martin Sandström on 2015-09-23.
// Copyright (c) 2015 Martin Sandström. All rights reserved.
//
#import "MSButtonTextTopCell.h"
@implementation MSButtonTextTopCell
-(id) init {
self = [super init];
if (self) {
}
return self;
}
-(id) initWithCoder:(NSCoder *)decoder {
return [super initWithCoder:decoder];
}
-(id) initImageCell:(NSImage *)image {
return [super initImageCell:image];
}
-(id) initTextCell:(NSString *)string {
return [super initTextCell:string];
}
- (NSRect)titleRectForBounds:(NSRect)theRect {
NSRect titleFrame = [super titleRectForBounds:theRect];
NSSize titleSize = [[self attributedStringValue] size];
titleFrame.origin.y = theRect.origin.y-(theRect.size.height-titleSize.height)*0.5;
return titleFrame;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment