macOS开发-NSImageView

一.简介

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");
    }
    
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容