【问题标题】:Layout UIView in center Device screen在中心设备屏幕中布局 UIView
【发布时间】:2015-01-31 17:08:18
【问题描述】:

我创建了一个自定义 UIView 并将其放入 viewcontroller 中,我想将它放置在所有设备(Ipad、Iphone)的中心

所以我这样做

CGRect screenRect = [[UIScreen mainScreen] bounds];

self.center = CGPointMake((screenRect.size.height/2),(screenRect.size.width/2));

但它只适用于 Ipad/lanscape

如何在所有设备、所有方向的中心屏幕上布局此视图

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    这不是一个好习惯,当视图是自定位时,你应该从你的 ViewController 执行此操作,例如在 viewWillAppear 中,检查你的 viewControllers 视图是否为全屏并执行此操作:

    CGRect rect = [self.view bounds];
    
    self.yoursView.center = CGPointMake((rect.size.width/2),(rect.height./2));
    

    【讨论】:

    • "width" 应该作为正确居中的第一个参数:CGPointMake((rect.size.width/2),(rect.size.height/2))
    • 是的,我没有注意到。
    • 或者你也可以使用CGPointMake(CGRectGetMidX(rect),CGRectGetMidY(rect))
    【解决方案2】:

    不确定我的答案是否是您正在寻找的,但按照我的看法,您必须将视图控制器视图的中心设置为自定义视图的中心。这应该发生在每个方向。

    具体来说,假设您有一个名为 testView 的自定义视图。

    最初在创建时您编写:

    self.testView.center = self.view.center;
    

    一种适用于 iOS 8 和之前版本的实用方法是观察 UIDeviceOrientationDidChangeNotification 通知,并在设备方向发生更改时收到通知。然后你可以再次设置自定义视图的中心,如上所示。

    例如,在 viewDidLoad 方法中让你的类观察上述通知:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOrientationChangeWithNotification:) name:UIDeviceOrientationDidChangeNotification object:nil];
    

    接下来,私下或公开声明 handleOrientationChangeWithNotification: 方法:

    @interface ViewController ()
    
    -(void)handleOrientationChangeWithNotification:(NSNotification *)notification;
    
    @end
    

    最后实现如下:

    -(void)handleOrientationChangeWithNotification:(NSNotification *)notification{
        self.testView.center = self.view.center;
    }
    

    现在,每次更改方向时,自定义视图都会定位到屏幕中心。

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-23
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多