1、基础创建

  • 代码
// 创建
NSImageView *image_view = [[NSImageView alloc] init];
// 位置尺寸
image_view.frame = NSMakeRect(30, 30, 150, 90);
// 添加
[self.window.contentView addSubview:image_view];
// 设置图片
image_view.image = [NSImage imageNamed:@"earth"];
// 是否可以编辑(设置可编辑边框会高亮)
image_view.editable = YES;
// 设置图片对齐方式
image_view.imageAlignment = NSImageAlignTop;
// 图像填充模式
image_view.imageScaling = NSImageScaleAxesIndependently;
// 图像边框
image_view.imageFrameStyle = NSImageFrameButton;
// 允许剪裁拷贝粘贴
image_view.allowsCutCopyPaste = YES;
  • 效果
  • Mac开发_NSImageView_macOS基础控件

2、给NSImageView添加点击事件

  • 子类化NSImageView然后覆盖他的mouseDown:方法

2.1 Basic_ImageView.h

#import <Cocoa/Cocoa.h>

NS_ASSUME_NONNULL_BEGIN

@interface Basic_ImageView : NSImageView

// 添加点击事件
- (void)addTarget:(nullable id)target
action:(SEL)action;

@end

NS_ASSUME_NONNULL_END

2.1 Basic_ImageView.m

#import "Basic_ImageView.h"

@interface Basic_ImageView ()

@property (nullable, weak) id gc_target;

@property (nullable) SEL gc_action;

@end

@implementation Basic_ImageView

- (void)addTarget:(nullable id)target
action:(SEL)action {
_gc_target = target;
_gc_action = action;
}

// 让imageview能够相应点击方法
- (void)mouseDown:(NSEvent *)event {
[super mouseDown:event];

if (_gc_target) {
[NSApp sendAction:_gc_action to:_gc_target from:self];
}
}

@end
  • 实现以上方法,就可以像按钮一样实现点击事件了。


作者:​​ CH520​