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;
if (@available(macOS 10.14, *)) {
image_view.contentTintColor = [NSColor whiteColor];
} else {
}
- 效果

2、给NSImageView添加点击事件
- 子类化NSImageView
-
2.1 GC_ImageView.h
#import <Cocoa/Cocoa.h>
NS_ASSUME_NONNULL_BEGIN
@interface GC_ImageView : NSImageView
- (void)addTarget:(nullable id)target
action:(SEL)action;
@property(nonatomic, copy) void(^mouseDown_Block)(void);
@property(nonatomic, copy) void(^mouseUp_Block)(void);
@end
NS_ASSUME_NONNULL_END
#import "GC_ImageView.h"
@interface GC_ImageView ()
@property (nullable, weak) id gc_target;
@property (nullable) SEL gc_action;
@end
@implementation GC_ImageView
- (void)addTarget:(nullable id)target
action:(SEL)action {
_gc_target = target;
_gc_action = action;
}
- (void)mouseDown:(NSEvent *)event {
[super mouseDown:event];
if (_gc_target) {
[NSApp sendAction:_gc_action to:_gc_target from:self];
}
if (self.mouseDown_Block) {
self.mouseDown_Block();
}
}
- (void)mouseUp:(NSEvent *)event {
if (self.mouseUp_Block) {
self.mouseUp_Block();
}
}
@end
GC_ImageView *image_view = [[GC_ImageView alloc] init];
image_view.frame = NSMakeRect(30, 30, 150, 90);
[self.window.contentView addSubview:image_view];
image_view.image = [NSImage imageNamed:@"12345678"];
image_view.mouseDown_Block = ^{
};
image_view.mouseUp_Block = ^{
};
NSClickGestureRecognizer *gesture = [[NSClickGestureRecognizer alloc] initWithTarget:self action:@selector(gesture_Tap:)];
[image_view addGestureRecognizer:gesture];
- (void)gesture_Tap:(NSGestureRecognizer *)gesture {
NSLog(@"touch view");
}
3、API说明
@interface NSImageView : NSControl <NSAccessibilityImage, NSMenuItemValidation>
+ (instancetype)imageViewWithImage:(NSImage *)image;
@property(nullable, strong) NSImage *image;
@property(getter=isEditable) BOOL editable;
@property NSImageAlignment imageAlignment;
@property NSImageScaling imageScaling;
@property NSImageFrameStyle imageFrameStyle;
@property(nullable, copy) NSImageSymbolConfiguration *symbolConfiguration;
@property(nullable, copy) NSColor *contentTintColor;
@property BOOL animates;
@property BOOL allowsCutCopyPaste;
@end
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库