CodexBloom - Programming Q&A Platform

How to implement guide with custom nsview subclass not redrawing after resizing in objective-c on macos 13

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-18
objective-c macos nsview Objective-C

I'm prototyping a solution and After trying multiple solutions online, I still can't figure this out... I'm working with a frustrating scenario with a custom subclass of NSView that fails to redraw itself correctly after resizing. The view is supposed to display a series of colored rectangles, but when I resize the window containing it, the rectangles don’t update as expected. Instead, I see remnants of the previous state. I've tried overriding the `setFrame:` and `drawRect:` methods to properly handle the resizing, but it still doesn’t behave correctly. Here's a simplified version of my code: ```objective-c @interface CustomView : NSView @end @implementation CustomView - (void)setFrame:(NSRect)frameRect { [super setFrame:frameRect]; [self setNeedsDisplay:YES]; } - (void)drawRect:(NSRect)dirtyRect { [super drawRect:dirtyRect]; NSColor *color = [NSColor blueColor]; [color setFill]; NSRectFill(dirtyRect); // Draw rectangles for (int i = 0; i < 5; i++) { NSRect rect = NSMakeRect(10, 10 + (i * 30), 100, 25); [[NSColor redColor] setFill]; NSRectFill(rect); } } @end ``` I also ensured that `setNeedsDisplay:YES` is called whenever the frame changes. However, I still see the old rectangles when I resize the window. I've tried adjusting the size calculations and ensuring that the dirty rect is correct, but nothing seems to work. Is there something I'm missing here in terms of view lifecycle or drawing context management? Any help would be greatly appreciated! What's the best practice here? Is this even possible?