objective-c - iPad/iPhone 旋转时旋转 subview

标签 objective-c ios cocoa-touch

我有一个以编程方式创建的状态/叠加 View ,当设备忙于执行某些任务时会弹出该 View 。我正在使用 [view addSubview: statusView] 将其添加到当前 View 。

当设备旋转时,statusView 会随设备旋转,因此文本会横向移动。我该如何更改以确保 subview 不会旋转,而是重新定位?

有一个similar SO question here这表明我可能需要实现一些方法来处理调整大小/重新定位,但它没有详细说明。

到目前为止,我正在屏幕外初始化 uiviewcontroller,如下所示,并在需要时将其移动到屏幕上:

- (id)initWithStatus:(NSString*)_status forWindow: (UIWindow*) window {
if (self = [super init]) {
    initialFrame = window.frame;
    visible = NO;
    barHeight = 40;

    // Create the status bar below the windows drawing area
    height = window.bounds.size.height;
    self.view = [[[UIView alloc] initWithFrame:CGRectMake(0, height, window.bounds.size.width, barHeight)]  autorelease];
    [self.view setBackgroundColor:[UIColor blackColor]];
    [self.view setAlpha:.5];

    // Add text text
    status = [[UILabel alloc] initWithFrame:CGRectMake(7, 7, window.bounds.size.width-14, barHeight-14)];
    status.font = [UIFont systemFontOfSize: 14];
    status.text = _status;
    status.textAlignment = UITextAlignmentCenter;
    status.backgroundColor = [UIColor clearColor];
    status.textColor = [UIColor whiteColor];
    [self.view addSubview:status];

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:)
                                                 name:UIDeviceOrientationDidChangeNotification object:nil];

}

return self;
}

在纵向时,可以使用以下方法轻松将其滑动到屏幕上:

-(void)updateStatus:(NSString*)_status {
if(visible) {
    status.text = _status;
    return;
}

visible = YES;
status.text = _status;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];

CGRect frame = self.view.frame;
frame.origin.y = height - barHeight;
self.view.frame = frame;
[UIView commitAnimations];
}

因此,当检测到方向变化时,这称为:

- (void)orientationChanged:(NSNotification *)notification {
    // Could just resize the box based on the new orientation but the text inside the box
    // runs the wrong direction instead of along the box.
}

最佳答案

如果您使用 UIViewController,则可以利用 autorotation .如果您的 View 不属于 View Controller ,通常您的自动调整大小蒙版将确保 View 仍然正确居中。如果您想手动重新定位它,可以通过观察 UIDeviceOrientationDidChangeNotification 来实现。 .

关于objective-c - iPad/iPhone 旋转时旋转 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7172143/

相关文章:

ios - 将地址转换为经度和纬度

ios - 如何在不请求许可的情况下获取用户的当前位置?

objective-c - 如何制作带有图标的内置应用程序?

ios - 使用 Parse 保存 CLCircularRegion

ios - 如何在 iOS 9 中使用 Swift 从 CMSampleBuffer 中提取像素数据进行处理?

iOS启动画面动画

ios - 将照片保存到照片库中的文件夹

iphone - 如何声明此应用程序的设备功能?

objective-c - Objective-C 对象的列表选择器

iphone - iPhone 中新联系人表单中的预填充字段和完成按钮将保存联系人