Question

I have an app where the user can add what I call palettes at will. Items (UIViews) can be dragged from one palette to another. I thought I could use the sizeToFit method to automatically resize the palettes when items were added ore removed, but no resizing seems to be happening.

The documentation states that the method resizes to the most appropriate size to fit the subviews. Does that not include UIViews that I add programmatically?

I'd really not have to write my own sizeToFit method if I can get the built-in one to work for me. But it seems to be doing nothing. Here's the code I've tried:

        CGPoint oldCenter = self.pieceBeingMoved.center;
        CGPoint newCenter = [self.pieceBeingMoved.superview convertPoint:oldCenter toView:destinationView];
        [destinationView addSubview:self.pieceBeingMoved];
        self.pieceBeingMoved.center = newCenter;
        if (destinationView.tag == 20000) {
           NSLog(@"DestinationView is a palette, so resize it from %@",NSStringFromCGRect(destinationView.frame));
           [destinationView sizeToFit];
           NSLog(@"DestinationView resized to %@",NSStringFromCGRect(destinationView.frame));
        }

The size is identical before and after the subview is added. The subview being added is the only subview at the time I ran this test, and the size of the subview is about 5% the size of the palette it is being moved to. So why isn't the view being resized? Do I need to do it myself?

Was it helpful?

Solution

The sizeToFit method just calls sizeThatFits: and then resizes the view accordingly. The default implementation of the UIView class returns the current size so you don’t see any effect. You will have to write your own sizeThatFits: method to do your calculation.

OTHER TIPS

Here's an idea. Don't call sizeToFit. Just set the frame to the frame you actually want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top