Mac OS 开发

MAC OSX - NSButton

2019-07-18  本文已影响0人  皮蛋豆腐酱油
  1. 添加点击事件:
    mac添加点击事件代码方法需要同时设置两个方法:
[self setTarget:targetObject ];
[self setAction: @selector(buttonClick:)];
  1. 改变文字颜色:
    mac的按钮不能像iOS一样直接设置文字颜色[self setTitleColor: forState:],需要如下设置
- (void)setButtonTitleColor:(NSColor *)color
{
    NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc] initWithAttributedString:[self attributedTitle]];
    NSUInteger len = [attrTitle length];
    NSRange range = NSMakeRange(0, len);
    [attrTitle addAttribute:NSForegroundColorAttributeName
                      value:color
                      range:range];
    [attrTitle fixAttributesInRange:range];
    [self setAttributedTitle:attrTitle];
}
  1. 改变背景颜色:
    mac的按钮不能像iOS一样直接设置背景颜色[self setBackgroundColor:],需要在layer层上设置
self.wantsLayer = YES;
self.layer.backgroundColor = [NSColor blueColor].CGColor;
  1. 点击不高亮:
 [(NSButtonCell *)self.cell setHighlightsBy:NSNoCellMask];
  1. 按钮不可点击:
    直接设置enabled = NO。不需要像iOS一样再手动设置按钮的文字颜色,mac会自动变成灰色文字。

  2. 不同状态的样式:
    设置按钮正常状态和点击后的图片不同,设置buttonType为Toggle,设置image和alternateImage,这样在正常状态就显示image的图片,在点击后就显示alternateImage的图片;
    设置按钮正常状态和点击时的图片不同,设置buttonType为change,设置image和alternateImage,这样在正常状态就显示image的图片,在点击时就显示alternateImage的图片;
    自定义类似系统关闭按钮那样的效果,就要自定义一个NSButton的子类,重写mouseDown,mouseEnter,mouseExit等方法。

  3. 鼠标悬停在按钮上出现提示文字:

self.toolTip = @"提示的文字";
  1. 设置按钮状态
    button.state  = NSControlStateValueOn;
一个NSButton的例子
    NSButton *chatBtn = [[NSButton alloc]initWithFrame:NSMakeRect(22, 420, 26, 26)];
    //设置按钮正常状态和点击后的图片不同,设置buttonType为Toggle,设置image和alternateImage
    [chatBtn setButtonType:NSButtonTypeToggle];
    [chatBtn setImage:[NSImage imageNamed:@"tab_chat"]];
    [chatBtn setAlternateImage:[NSImage imageNamed:@"tab_chat_selected"]];
    [chatBtn setImageScaling:NSImageScaleAxesIndependently];
    [chatBtn setTitle:@""];
    [chatBtn setBordered:false];  //不显示边框
    //裁剪成圆形
    [chatBtn setWantsLayer:true];
    chatBtn.layer.masksToBounds = true;
    chatBtn.layer.cornerRadius = 13;
    chatBtn.state  = NSControlStateValueOn;    //设置按钮状态
    [chatBtn setTarget:self];
    [chatBtn setAction:@selector(clickChatBtn:)];
    [self.leftMenuView addSubview:chatBtn];

    - (void)clickChatBtn:(id)sender {
        NSLog(@"clickChatBtn");
    }

链接:https://www.jianshu.com/p/c09c715b1617

上一篇下一篇

猜你喜欢

热点阅读