要使 UIView 在“屏幕”中居中,您需要将其相对于根视图控制器的视图居中。如果您以编程方式对 UIView 或其子类(例如 ImageView)进行子类化,并且您的超级视图不是视图控制器的视图,这将非常有用。这是一种将视图置于根视图中心的方法,无论它位于视图层次结构中的什么位置:
// center the view in the root view
- (void)centerInRootview:UIView *view {
UIView *rootview = UIApplication.sharedApplication.keyWindow.rootViewController.view;
// if the view hierarchy has not been loaded yet, size will be zero
if (rootview.bounds.size.width > 0 &&
rootview.bounds.size.height > 0) {
CGPoint rootCenter = CGPointMake(CGRectGetMidX(rootview.bounds),
CGRectGetMidY(rootview.bounds));
// center the view relative to it's superview coordinates
CGPoint center = [rootview convertPoint:rootCenter toView:view.superview];
[view setCenter:center];
}
}
这使用UIView.convertPoint:toView 方法将根视图的坐标系转换为您的视图的父视图的坐标系。
我在UIView 类别中使用此方法,以便它可以从任何UIView 子类中使用。这里是View.h:
//
// View.h - Category interface for UIView
//
#import <UIKit/UIKit.h>
@interface UIView (View)
- (void)centerInRootview;
@end
和 View.m:
//
// View.m - Category implementation for UIView
//
#import "View.h"
@implementation UIView (View)
// center the view in the root view
- (void)centerInRootview {
// make sure the view hierarchy has been loaded first
if (self.rootview.bounds.size.width > 0 &&
self.rootview.bounds.size.height > 0) {
CGPoint rootCenter = CGPointMake(CGRectGetMidX(self.rootview.bounds),
CGRectGetMidY(self.rootview.bounds));
// center the view in it's superview coordinates
CGPoint center = [self.rootview convertPoint:rootCenter toView:self.superview];
[self setCenter:center];
}
}
@end
这里有一个简单的例子,说明如何从 UIImageView 子类中使用它。 ImageView.h:
//
// ImageView.h - Example UIImageView subclass
//
#import <UIKit/UIKit.h>
@interface ImageView : UIImageView
- (void)reset;
@end
还有 ImageView.m:
#import "ImageView.h"
@implementation ImageView
- (void)reset {
self.transform = CGAffineTransformIdentity;
// inherited from UIImageView->UIView (View)
[self centerInRootview];
}
@end