【问题标题】:iOS: Adjust Height of UIWebView - Strange BehaviouriOS:调整 UIWebView 的高度 - 奇怪的行为
【发布时间】:2013-04-17 14:33:44
【问题描述】:

我有一个问题。在 Xcode 我有一个 ViewController 嵌入 View > ScrollView 并且 Scrollview 内部是一个 UIWebView。

应用程序读取一些 XML 数据并将格式化文本粘贴到 UIWebViewUIWebView-Element之后是另一个Element,所以我必须动态调整UIWebView的高度。

加载视图后一切正常,但是当我点击屏幕时,视图将scrollview 重新调整为故事板高度。

为什么?

- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{
aWebView.scrollView.scrollEnabled = NO;    // Property available in iOS 5.0 and later
CGRect frame = aWebView.frame;

frame.size.width = 280;       // Your desired width here.
frame.size.height = 1;        // Set the height to a small one.

aWebView.frame = frame;       // Set webView's Frame, forcing the Layout of its embedded     scrollView with current Frame's constraints (Width set above).

frame.size.height = aWebView.scrollView.contentSize.height;  // Get the corresponding         height from the webView's embedded scrollView.

aWebView.frame = frame;       // Set the scrollView contentHeight back to the frame itself.

NSLog(@"size: %f, %f", aWebView.frame.size.width, aWebView.frame.size.height);

// Position URL Label
CGRect frame_label = fachmesseDetailWebsite.frame;
NSLog(@"x: %f", frame_label.origin.x);
NSLog(@"y: %f", frame_label.origin.y);
frame_label.origin.y=aWebView.frame.size.height+115;//pass the cordinate which you want
frame_label.origin.x= 20;//pass the cordinate which you want
fachmesseDetailWebsite.frame= frame_label;
NSLog(@"x: %f", frame_label.origin.x);
NSLog(@"y: %f", frame_label.origin.y);

}

【问题讨论】:

    标签: ios xcode uiwebview scrollview


    【解决方案1】:

    每当您更改框架时,您必须重新加载 webview,然后只有 webview 框架会更改您放置的任何内容,否则它不会影响 webview。

    [webview reload];
    

    编辑: 这个工作

    UIWebView *web=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    
        NSString* html = [NSString stringWithFormat:@"<html><head><style>a { color: #db5226; text-decoration: none; font-weight: bold; } body { padding: 0; margin: 0; font-size:45px;font-family: Helvetica;text-align:left; color:black; } </style></head<body>%@</body></html>",@"helow"];
        [web loadHTMLString:html baseURL:nil];
        [self.view addSubview:web];
    

    【讨论】:

    • 谢谢。这是我将内容添加到 webview 的方法:NSString* html = [NSString stringWithFormat:@"&lt;html&gt;&lt;head&gt;&lt;style&gt;a { color: #db5226; text-decoration: none; font-weight: bold; } body { padding: 0; margin: 0; font-size:13px;font-family: Helvetica;text-align:left; color:black; } &lt;/style&gt;&lt;/head&lt;body&gt;%@&lt;/body&gt;&lt;/html&gt;",item.description]; [self.fachmesseDetailText loadHTMLString:html baseURL:nil]; 当我重新加载 webview 时,everythink 都是空白的......
    • 不能使用放在storyboard中的webview吗?
    • 你可以在storyboard应用中添加webview没问题。