macOS开发-NSImageView
2020-10-28 本文已影响0人
ForgetSou
一.简介
NSImageView
和iOS的UIImageView
类似,只有添加手势时有些不一样。macOS中NSImageView
没有userInteractionEnabled
,不能添加gesture。
二.示例
要想给NSImageView
添加手势有2种方式
-
需要创建一个子类集成
NSImageView
,重写mouseDown、mouseUp等方法。// FSImageView.h #import <Cocoa/Cocoa.h> @interface FSImageView : NSImageView @property (copy, nonatomic) void(^mouseDownBlock)(void); @property (copy, nonatomic) void(^mouseUpBlock)(void); @end // FSImageView.m #import "FSImageView.h" @implementation FSImageView - (void)drawRect:(NSRect)dirtyRect { [super drawRect:dirtyRect]; // Drawing code here. } - (void)mouseDown:(NSEvent *)event { if (self.mouseDownBlock) { self.mouseDownBlock(); } } - (void)mouseUp:(NSEvent *)event { if (self.mouseUpBlock) { self.mouseUpBlock(); } } @end // ViewController.m FSImageView *imgView = [[FSImageView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)]; imgView.image = [NSImage imageNamed:@"avator"]; // 设置背景色 imgView.wantsLayer = YES; imgView.layer.backgroundColor = NSColor.redColor.CGColor; // 设置圆角 imgView.layer.cornerRadius = 100; // 设置边框 imgView.layer.borderColor = NSColor.redColor.CGColor; imgView.layer.borderWidth = 5; // 添加手势 imgView.mouseDownBlock = ^{ // 按下 }; imgView.mouseUpBlock = ^{ // 抬起 }; [self.view addSubview:imgView];
-
为
NSImageView
添加手势NSGestureRecognizer// NSGestureRecognizer的子类来确定使用哪种手势 /*! NSClickGestureRecognizer 单点 NSPanGestureRecognizer 拖动 NSMagnificationGestureRecognizer 放大 NSPressGestureRecognizer 按压 NSRotationGestureRecognizer 旋转 */ FSImageView *imgView = [[FSImageView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)]; imgView.image = [NSImage imageNamed:@"avator"]; // 设置背景色 imgView.wantsLayer = YES; imgView.layer.backgroundColor = NSColor.redColor.CGColor; // 设置圆角 imgView.layer.cornerRadius = 100; // 设置边框 imgView.layer.borderColor = NSColor.redColor.CGColor; imgView.layer.borderWidth = 5; // 添加手势 NSClickGestureRecognizer *gesture = [[NSClickGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewClick:)]; [view addGestureRecognizer:gesture]; [self.view addSubview:imgView]; - (void)imageViewClick:(NSGestureRecognizer *)gesture { NSLog(@"touch view"); }