如何以编程方式在根视图中居中放置iOS UIView子视图?

时间:2018-10-01 20:38:24

标签: ios objective-c uiview uiimageview

有很多关于UIView的中心问题和答案,但是我没有找到符合我的条件的问题。我有一个UIImageView子类,它是另一个(相同)UIImageView子类的子视图。我需要能够“重置” UIImageView子类,以便在用户交互时它位于屏幕(根视图控制器的视图)的中心。

只需这样做:

- (void)reset {
    [self setCenter: self.superview.center];
}

...不起作用,因为中心点位于超级视图的坐标系中,而不是根视图。可以将超级视图拖离根视图的中心。

最初,我循环通过超级视图层次结构来查找根视图,但仍然无法正常工作,再次是因为用户可以在嵌套视图的每个级别上将其应用于每个UIImageView子类的坐标系和比例不同

我没有找到关于SO的完整解决方案,因此我编写了自己的解决方案并将其发布在这里。希望它可以节省其他人的时间,从而节省时间。

1 个答案:

答案 0 :(得分:0)

要将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