更改NSButton的高度,使用的默认的button
如图所示,interfaceBuilder中拖入一个button以后,button的frame属性Height被系统锁死,无法更改。
经过多次尝试,终于在一个阴暗的角落发现了button的高度修改方法,请看图:
Bug一、更改NSButton的背景色
```
@interfaceYHNButton :NSButton
@property(nonatomic,strong)NSColor*backgroundColor;
@property(nonatomic,strong)NSColor*titleColor;
@end
- (void)drawRect:(NSRect)dirtyRect
{
;
[superdrawRect:dirtyRect];
if(self.backgroundColor!=nil) {
[self.backgroundColorset];
NSRectFill(self.bounds);
}
//绘制文字 , 排版乱了,复制到xcode,自行排版吧
if(self.title!=nil) {
NSColor*color =self.titleColor?self.titleColor: [NSColorblackColor];
NSMutableParagraphStyle*paraStyle = [[NSMutableParagraphStylealloc]init];
[paraStylesetParagraphStyle:[NSParagraphStyledefaultParagraphStyle]];
[paraStylesetAlignment:NSCenterTextAlignment];
//[paraStyle setLineBreakMode:NSLineBreakByTruncatingTail];
NSDictionary*attrButton = [NSDictionary dictionaryWithObjectsAndKeys:[NSFontfontWithName:@"Verdana"size:14],NSFontAttributeName, color,NSForegroundColorAttributeName, paraStyle,NSParagraphStyleAttributeName,nil];
NSAttributedString* btnString = [[NSAttributedString alloc]initWithString:self.titleattributes:attrButton];
[btnString drawInRect:NSMakeRect(0,4,self.frame.size.width,self.frame.size.height)];
}
}
```
确实有效,但是这样写岂不是太累了 ,而且还得重新绘制title ,简直了... 希望有更好的方法
button 鼠标移入移出 不同的效果 ,实现框架 ,这里是切换不同图片
- (void)awakeFromNib {
NSTrackingArea *area =[[NSTrackingAreaalloc]initWithRect:self.boundsoptions:NSTrackingMouseEnteredAndExited|NSTrackingActiveInKeyWindowowner:selfuserInfo:nil];
[selfaddTrackingArea:area];
}
- (void)mouseEntered:(NSEvent *)event {
self.image = [NSImageimageNamed:@"btn3"];
}
- (void)mouseExited:(NSEvent *)event {
self.image = [NSImageimageNamed:@"btn2"];
}
修改Button颜色的另一种思路 , 修改buttoncell ,
根据界面的需要设置不同颜色的title。之前一直进入一个误区,直接自定义NSButton控件,其实这个方法是不好的,会使title重绘多次,复用性不高。
后来发现直接自定义NSButtonCell,可以只对title进行处理就可以了,而不必影响NSButton的其他属性。
下面是自定义NSButtonCell的方法。
直接把NSButton
中的NSBUttonCell的Class改为MqjColorTitleButton, 然后其他操作不变 ,
但是有一个问题, 这个颜色是写死的, 怎么把颜色值传入呢, 我的想法是在cell中加一个NSColor属性,
@property(nonatomic,strong)NSColor * titleColor ;
确实可以, 但是每次调用都要这样写
// ButtonCell * cell = self.button.cell ;
// cell.titleColor = [NSColor yellowColor] ;
也很麻烦 , 这个好弄 ,在 继承的Button里在写一个@property(nonatomic,strong)NSColor * titleColr ;
属性, 然后重写
- (void)setTitleColr:(NSColor *)titleColr {
_titleColr = titleColr;
ButtonCell * cell =self.cell;
cell.titleColor = titleColr ;
}
这样在外面调用的时候,就是self.button.titleColr = [NSColororangeColor];
方便多了.