ForgetSou | Blog

❤ 武统台湾 刻不容缓 ❤

0%

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");
    }
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道