如何在物镜c中设备旋转后更新Web视图宽度?

  • 本文关键字:Web 更新 视图 旋转 ios webview
  • 更新时间 :
  • 英文 :


当我第一次加载网络视图时,它的框架是正确的,但是当我旋转设备时,它的宽度没有更新。
例如,如果视图是纵向的,而我横向旋转它,则 Web 视图框架不会覆盖整个视图。

加载网页视图

-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self loadWebView];
}
-(void) loadWebView {
UIWebView *webView;
webView = [[UIWebView alloc] initWithFrame: self.view.frame];
NSString *htmlString = [NSString stringWithFormat:@"%@%@%@",html_header_with_files,DetailsHtml,HTML_FOOTER];
[webView loadHTMLString:htmlString baseURL:nil];
[self.view addSubview:webView];
}

第一次尝试:我添加了通知以实现旋转

- (void) orientationChanged:(NSNotification *)note
{
[self.view layoutIfNeeded];
}

上面的代码没有解决问题。


第二次尝试

- (void) orientationChanged:(NSNotification *)note
{
[self loadWebView];
}

上面的代码没有解决问题。

视图必须添加自动布局,以便在具有两个方向的所有设备中正确布局。

您需要创建 UIView 的扩展并添加以下方法以使其成为可重用的代码。如果不打算在其他任何地方使用此方法,也可以在同一类中添加该方法。

- (void)addSubView:(UIView *)subView belowView:(UIView *)belowView inSuperView:(UIView *)superView {
[superView addSubview:subView];
[superView addConstraint:[NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
[superView addConstraint:[NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
[superView addConstraint:[NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
if (nil == belowView) {
[superView addConstraint:[NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
} else {
[superView addConstraint:[NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:belowView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
}
}

然后你需要调用上面的方法,比如

[self addSubView:webView belowView:nil inSuperView:self.view];

注意:

要了解有关自动布局的更多信息,您可以按照教程进行操作

https://www.raywenderlich.com/443-auto-layout-tutorial-in-ios-11-getting-started

此外,最好开始使用swift开始编写应用程序,而不是继续使用objective-c,即使您的某些代码库已经在objective-c中。使obj-c和快速互操作性的教程可以在下面的链接中看到

https://medium.com/ios-os-x-development/swift-and-objective-c-interoperability-2add8e6d6887

最新更新