macOS开发 NSSegmentedControl

先看效果

 

 直接复制代码运行

#import "ViewController.h"

@interface ViewController ()

///分段控制器
@property (nonatomic, strong) NSSegmentedControl *MenuViewSegment;

@end

@implementation ViewController

#pragma mark 懒加载
- (NSSegmentedControl*)MenuViewSegment{
    if(!_MenuViewSegment){
//        _MenuViewSegment = [[NSSegmentedControl alloc] init];
//        [self.view addSubview:self.MenuViewSegment];
        NSSegmentedControl *lbl = [[NSSegmentedControl alloc] init];
        [self.view addSubview:lbl];
        _MenuViewSegment = lbl;
    }
    return _MenuViewSegment;
}


-(void)viewDidLoad {
    [super viewDidLoad];
    _MenuViewSegment.frame = NSMakeRect(100, 100, 200, 100);
    
    _MenuViewSegment.segmentCount = 3;//Segment数量
    [_MenuViewSegment setLabel:@"" forSegment:0];//显示文字和下标位置

    
    [_MenuViewSegment setImage:[NSImage imageNamed:NSImageNameUser] forSegment:1];//显示图片和下标位置
    [_MenuViewSegment setImageScaling:NSImageScaleProportionallyDown forSegment:1];

    NSMenu *subMenu = [[NSMenu alloc] init];
    
    //常规添加菜单
    [subMenu insertItemWithTitle:@"Item 1"action:@selector(beep:)keyEquivalent:@""atIndex:0];

    [subMenu insertItemWithTitle:@"Item 2"action:@selector(beep:)keyEquivalent:@""atIndex:1];
    [_MenuViewSegment setLabel:@"Item 1" forSegment:2];
    
    [_MenuViewSegment setMenu:subMenu forSegment:2];//显示菜单和下标位置
    [_MenuViewSegment setWidth:100 forSegment:2];//设置下标的宽度

 //[_MenuViewSegment setAction:@selector(segmentControlChange:)];//Segment各个项目菜单点击方法,NSMenuItem的beep:会冲突
}

#pragma mark 统一使用响应方法,不然不使用该方法的菜单栏将不能点击
-(void)beep:(NSMenuItem *)menuItem{

    NSLog(@"_____%@", menuItem);
    
    [self.MenuViewSegment setLabel:menuItem.title forSegment:2];
}



#pragma mark Segment各个项目菜单点击方法响应方法,和NSMenuItem会冲突
- (void)segmentControlChange:(NSSegmentedControl *)segControl{

    NSLog(@"tag : %ld , selectedSegment : %ld",segControl.tag,segControl.selectedSegment);
    
}

 

posted on 2022-10-11 09:58  高彰  阅读(154)  评论(0编辑  收藏  举报

导航