一.简介
NSView
用于在应用程序中渲染、打印以及处理事件的基础容器,多数功能由AppKit自动调用。
NSView
继承自NSResponder
@interface NSView : NSResponder <NSAnimatablePropertyContainer, NSUserInterfaceItemIdentification, NSDraggingDestination, NSAppearanceCustomization, NSAccessibilityElement, NSAccessibility>
|
通常我们不直接使用NSView
,而是创建子类或派生对象实现我们的需求。
@property (nullable, readonly, assign) NSWindow *window;
|
二.核心API
1.创建对象
- (instancetype)initWithFrame:(NSRect)frameRect NS_DESIGNATED_INITIALIZER; - (void)prepareForReuse API_AVAILABLE(macos(10.7));
|
2.视图结构
@property (nullable, readonly, assign) NSWindow *window; @property (nullable, readonly, assign) NSView *superview; @property (copy) NSArray<__kindof NSView *> *subviews;
- (BOOL)isDescendantOf:(NSView *)view;
- (nullable NSView *)ancestorSharedWithView:(NSView *)view;
@property (nullable, readonly, assign) NSView *opaqueAncestor;
- (void)addSubview:(NSView *)view; - (void)addSubview:(NSView *)view positioned:(NSWindowOrderingMode)place relativeTo:(nullable NSView *)otherView;
- (void)didAddSubview:(NSView *)subview;
- (void)removeFromSuperview;
- (void)willRemoveSubview:(NSView *)subview;
- (void)replaceSubview:(NSView *)oldView with:(NSView *)newView;
- (void)sortSubviewsUsingFunction:(NSComparisonResult (NS_NOESCAPE *)(__kindof NSView *, __kindof NSView *, void * _Nullable))compare context:(nullable void *)context;
- (void)viewWillMoveToWindow:(nullable NSWindow *)newWindow;
- (void)viewDidMoveToWindow;
- (void)viewWillMoveToSuperview:(nullable NSView *)newSuperview;
- (void)viewDidMoveToSuperview;
|
3.frame & bounds
- (void)setFrameOrigin:(NSPoint)newOrigin; - (void)setFrameSize:(NSSize)newSize; @property NSRect frame; @property CGFloat frameRotation; @property CGFloat frameCenterRotation API_AVAILABLE(macos(10.5));
- (void)setBoundsOrigin:(NSPoint)newOrigin; - (void)setBoundsSize:(NSSize)newSize; @property CGFloat boundsRotation; - (void)translateOriginToPoint:(NSPoint)translation; - (void)scaleUnitSquareToSize:(NSSize)newUnitSize; - (void)rotateByAngle:(CGFloat)angle; @property NSRect bounds;
|
3.简单示例
NSView *view = [[NSView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)]; [view prepareForReuse];
view.wantsLayer = YES; view.layer.backgroundColor = NSColor.redColor.CGColor;
view.layer.cornerRadius = 100;
view.layer.borderColor = NSColor.greenColor.CGColor; view.layer.borderWidth = 3; NSClickGestureRecognizer *gesture = [[NSClickGestureRecognizer alloc] initWithTarget:self action:@selector(viewClick:)]; [view addGestureRecognizer:gesture]; [self.view addSubview:view];
- (void)viewClick:(NSGestureRecognizer *)gesture { NSLog(@"touch view"); }
|