Jeremy L
Jeremy L

Reputation: 3810

On iOS, what is the best way to set up a subview if we really would like to do initWithCenterAndSize?

For example, if we are to draw a 100 x 100 pixel circle on the main view which covers up the whole screen on the iPad, then instead of using initWithFrame like following 2 steps in viewDidLoad:

UINodeView *nodeView = [[UINodeView alloc] initWithFrame:
                               CGRectMake(x, y, NSNodeWidth, NSNodeHeight)];
nodeView.center = CGPointMake(x, y);

because x and y is more elegantly as self.view.bounds.size.width / 2 to horizontally center the circle, instead of self.view.bounds.size.width / 2 - NSNodeWidth / 2. Is init by a frame first, and then reset the center a good way, or is there a better way, if there is a initWithCenterAndSize?

Upvotes: 0

Views: 88

Answers (2)

Jeffery Li
Jeffery Li

Reputation: 565

I usually do this:

UINodeView *nodeView = [[UINodeView alloc] initWithFrame:
                           CGRectMake(0, 0, NSNodeWidth, NSNodeHeight)];
nodeView.center = CGPointMake(x, y);

It looks nice and clear.

Upvotes: 1

deanWombourne
deanWombourne

Reputation: 38485

That's a fine way of doing it :)

I would have gone for generating the positioned frame first to avoid the extra method call but that's just a matter of personal preference :)

If you're using this alot in your app you could make a category on UIView that implements this (warning, untested code :)

- (id)initWithCenter:(CGPoint)point size:(CGSize)size {
    CGRect frame = CGRectMake(point.x-size.width/2,
                              point.y-size.height/2, 
                              size.width,
                              size.height);
    return [self initWithFrame:frame];
}

Upvotes: 1

Related Questions