简体   繁体   中英

Trying to center a view within its superview

I am creating a category on UIView to make programmatically positioning and sizing my views easier. I want to create a method that will center a given view horizontally or vertically in its superview . So I can do something like the following:

Category

- (void)centerHorizontally {
    self.center = CGPointMake(self.window.superview.center.x, self.center.y);
}

- (void)centerVertically {
    self.center = CGPointMake(self.center.x, self.window.superview.center.y);
}

Use

UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[v centerHorizontally];

However, this doesn't seem to be working. What is incorrect about my solution?

You need to add the view to a parent view before you can center it.

UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[someOtherView addSubview:v];
[v centerHorizontally];

And your category is incorrect. Don't get the window involved. You need to base it on the superview's size:

- (void)centerHorizontally {
    self.center = CGPointMake(self.superview.bounds.size.width / 2.0, self.center.y);
    // or
    self.center = CGPointMake(CGRectGetMidX(self.superview.bounds), self.center.y);
}

- (void)centerVertically {
    self.center = CGPointMake(self.center.x, self.superview.bounds.size.height / 2.0);
    // or
    self.center = CGPointMake(self.center.x, CGRectGetMidY(self.superview.bounds));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM