[Cocoa]_[初级]_[NSButton之改变title标题的颜色]

来源:互联网 发布:软件设计师官网 编辑:程序博客网 时间:2024/05/21 16:22

场景:用于布局控件,根据界面的需要设置不同颜色的title。之前一直进入一个误区,直接自定义NSButton控件,其实这个方法是不好的,会使title重绘多次,复用性不高。

后来发现直接自定义NSButtonCell,可以只对title进行处理就可以了,而不必影响NSButton的其他属性。

下面是自定义NSButtonCell的方法。

MqjColorTitleButtonCell.h#import <Cocoa/Cocoa.h>@interface MqjColorTitleButtonCell : NSButtonCell@endMqjColorTitleButtonCell.m
<pre name="code" class="objc">#import "MqjColorTitleButtonCell.h"@implementation MqjColorTitleButtonCell- (NSRect)drawTitle:(NSAttributedString *)title withFrame:(NSRect)frame inView:(NSView *)controlView{        NSSize titleSize =  [title size];        //居中显示    CGFloat titleY = frame.origin.y + (frame.size.height - titleSize.height)/2;    NSRect rectTitle = frame;        rectTitle.origin.y = titleY;       NSMutableAttributedString *titleStr =[[NSMutableAttributedString alloc]                                            initWithAttributedString:title];    [titleStr addAttribute:NSForegroundColorAttributeName value:[NSColor redColor]                                             range:NSMakeRange(0, titleStr.length)];    [titleStr drawInRect:rectTitle];    [titleStr release];        return frame;}@end


直接把NSButton

中的NSBUttonCell的Class改为MqjColorTitleButton,然后其他操作不变。



0 0
原创粉丝点击