美文网首页macOS开发
macOS开发-NSImageView

macOS开发-NSImageView

作者: ForgetSou | 来源:发表于2020-10-28 14:04 被阅读0次

    一.简介

    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");
      }
      

    相关文章

      网友评论

        本文标题:macOS开发-NSImageView

        本文链接:https://www.haomeiwen.com/subject/nydamktx.html