Dynamic UIView height with auto layout in iOS 6

后端 未结 2 1224
清歌不尽
清歌不尽 2020-12-12 16:12

For the last couple of days I am trying to accomplish a fairly simple (at least it should be) layout using auto layout constraints, but without success.

My view

相关标签:
2条回答
  • 2020-12-12 16:33

    You might need a delay before updating webview content size. And masonry is useful for autolayout usage.

    -(void)webViewDidFinishLoad:(UIWebView *)webview{
        [self performSelector:@selector(checkContentOnDelay:) withObject:webview afterDelay:0.001];
    }
    
    -(void)checkContentOnDelay:(UIWebView *)webview{
        CGSize contentSize = webview.scrollView.contentSize;
        if (contentSize.height > 2) {
            [webview updateConstraints:^(MASConstraintMaker *make) {
                make.height.equalTo(contentSize.height);
            }];
        }else{
            [self performSelector:@selector(checkContentOnDelay:) withObject:webview afterDelay:0.01];
        }
    }
    
    0 讨论(0)
  • 2020-12-12 16:39

    You are setting the height contraint of your webView as 266. That's why the height of the web view is still fixed.

    You can create this height constraint as an IBOutlet, for example:

    @property (weak, nonatomic) IBOutlet NSLayoutConstraint *webViewHeightConstraint;
    

    And then you can modify the constant of the height constraint when the web view has finished downloading the content. The web view itself consists of scroll view inside, so if you want to get the overall height of the content:

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        self.webViewHeightConstraint.constant = self.webView.scrollView.contentSize.height;
    }
    

    Or apparently this one also works:

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        [self.webView sizeToFit];
        self.webViewHeightConstraint.constant = self.webView.frame.size.height;
    }
    
    0 讨论(0)
提交回复
热议问题