Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using AppKit;
using Foundation;
using System;
using CoreGraphics;
namespace NSViewChainTestManaged
{
public class CustomView : NSView
{
public string Name { get; set; }
public NSColor BackgroundColor {
get {
return NSColor.FromCGColor (Layer.BackgroundColor);
}
set {
WantsLayer = true;
Layer.BackgroundColor = value.CGColor;
}
}
public CustomView (CGRect r) : base (r)
{
}
public CustomView (IntPtr p) : base (p)
{
}
public override void RemoveFromSuperview ()
{
base.RemoveFromSuperview ();
Console.WriteLine ("{0} Removed", Name);
}
}
[Register ("AppDelegate")]
public class AppDelegate : NSApplicationDelegate
{
public AppDelegate ()
{
}
public override void DidFinishLaunching (NSNotification notification)
{
CustomView parent = new CustomView (new CGRect (20, 20, 200, 200));
parent.Name = "Blue";
parent.BackgroundColor = NSColor.Blue;
CustomView child = new CustomView (new CGRect (20, 20, 50, 50));
child.Name = "Red";
child.BackgroundColor = NSColor.Red;
parent.AddSubview (child);
NSApplication.SharedApplication.MainWindow.ContentView.AddSubview (parent);
NSButton b = new NSButton (new CGRect (300, 20, 100, 25));
b.Activated += (object sender, EventArgs e) => {
NSApplication.SharedApplication.MainWindow.ContentView.Subviews[0].RemoveFromSuperview ();
};
NSApplication.SharedApplication.MainWindow.ContentView.AddSubview (b);
}
}
}
//
// AppDelegate.m
// NSViewChainTest
//
// Created by Chris Hamons on 9/29/15.
// Copyright © 2015 Chris Hamons. All rights reserved.
//
#import "AppDelegate.h"
@interface CustomView()
@property (nonatomic, retain) NSString *name;
@property (nonatomic, assign) NSColor *backgroundColor;
@end
@implementation CustomView
- (void)removeFromSuperview
{
[super removeFromSuperview];
NSLog(@">>>> %@ is removed from super view", self.name);
}
- (void)setBackgroundColor:(NSColor *)backgroundColor
{
self.wantsLayer = YES;
self.layer.backgroundColor = backgroundColor.CGColor;
}
@end
@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
CustomView * parent = [[CustomView alloc] initWithFrame:NSMakeRect(20, 20, 200, 200)];
parent.name = @"Blue";
parent.backgroundColor = [NSColor blueColor];
CustomView * child = [[CustomView alloc] initWithFrame:NSMakeRect(20, 20, 50, 50)];
child.name = @"Red";
child.backgroundColor = [NSColor redColor];
[parent addSubview:child];
[self.window.contentView addSubview:parent];
NSButton * b = [[NSButton alloc] initWithFrame:NSMakeRect(300, 20, 100, 25)];
b.target = self;
b.action = @selector(onPress);
[self.window.contentView addSubview:b];
}
- (void)onPress
{
[self.window.contentView.subviews[0] removeFromSuperview];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment