Resizing a Cocoa window

Test for source code quotation

The following code shows how to resize a Cocoa window to fit with the content size. Blah blah.

- (IBAction)resizeWindow:(id)sender {
	NSLog(@"resize window to %dx%d", width, height);
	NSRect rectNewFrame = [[self window] frameRectForContentRect:NSMakeRect(0, 0, width, height)];
	NSRect rect = [[self window] frame];
	//rectNewFrame.origin = NSMakePoint(
	//	rect.origin.x,
	//	rect.origin.y + rect.size.height - rectNewFrame.size.height);
	rectNewFrame.origin = NSMakePoint(
		rect.origin.x + .5f * (rect.size.width - rectNewFrame.size.width),
		rect.origin.y + .5f * (rect.size.height - rectNewFrame.size.height));
	// maybe needs to consider the margin around the view
	[[self window] setFrame:rectNewFrame display:YES animate:YES];

That’s it. Refer to this post for more details:

Resizing a Cocoa window