代码之家  ›  专栏  ›  技术社区  ›  Fattaneh Talebi

如何在objective c中更新设备旋转后的web视图宽度?

  •  0
  • Fattaneh Talebi  · 技术社区  · 8 年前

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

    加载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];
    }
    


    1 回复  |  直到 8 年前
        1
  •  1
  •   Karthick Ramesh    8 年前

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

    您需要创建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中了

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