自定义NSButton

//MyButton.h

@interface MyButton : NSButton

@property (assign)BOOL isSelected;//可以用来切换图片

+ (MyButton *)initWithTitle:(NSString *)title image:(NSImage *)image target:(id)target action:(SEL)action buttonType:(NSCellImagePosition)buttonType;

@end

//MyButton.m

@implementation JDSCoreButton

+ (MyButton *)initWithTitle:(NSString *)title image:(NSImage *)image target:(id)target action:(SEL)action buttonType:(NSCellImagePosition)buttonType {

    MyButton *button;

    if (image) {

        image.size = NSMakeSize(22, 22);

        if (title) {

            button = [JDSCoreButton buttonWithTitle:title image:image target:target action:action];

        }else {

            buttonType =NSImageOnly;

            button = [JDSCoreButton buttonWithImage:image target:target action:action];

        }

    }else if(title){

        button = [JDSCoreButton buttonWithTitle:title target:target action:action];

    }

    // 创建Attributes,设置颜色和段落样式

    if (title) {

        // 创建段落样式,主要是为了设置居中

        NSMutableParagraphStyle *pghStyle = [[NSMutableParagraphStyle alloc] init];

        pghStyle.alignment = NSTextAlignmentCenter;

        // 创建Attributes,设置title颜色和段落样式

        NSDictionary *dicAtt = @{NSForegroundColorAttributeName: [NSColor whiteColor], NSParagraphStyleAttributeName: pghStyle};

        NSMutableAttributedString *attributedString=[[NSMutableAttributedString alloc] initWithString:title attributes:nil];

        [attributedStringsetAttributes:dicAtt range:NSMakeRange(0, title.length)];

        button.attributedTitle = attributedString;

    }

    if (buttonType) {

        [buttonsetImagePosition:buttonType];

    }else {

        [buttonsetImagePosition:NSImageAbove];

    }

    [buttonsetBordered:NO];

    button.isSelected = NO;

    return button;

}

@end

使用:

_towardsLeftBtn = [MyButton initWithTitle:nil image:[NSImage imageNamed:@"zuo_gray"] target:self action:@selector(towardsLeftBtnClick:) buttonType:nil];

    [self.view addSubview:_towardsLeftBtn];

    [_towardsLeftBtn mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(5);

        make.right.mas_equalTo(_towardsBottomBtn.mas_left).mas_offset(-30);

        make.width.mas_equalTo(30);

        make.height.mas_equalTo(30);

    }];

- (void)towardsLeftBtnClick:(id)sender{

    _towardsLeftBtn.image = _towardsLeftBtn.isSelected ? [NSImage imageNamed:@"zuo_gray"] : [NSImage imageNamed:@"zuo_red"];

    _towardsLeftBtn.isSelected = !_towardsLeftBtn.isSelected;

}

你可能感兴趣的:(自定义NSButton)