2013-08-20 35 views
9

目標:匹配子視圖的寬度到它的使用上海華自動版式

有一個UIWebView具有相同的寬度,因爲它是上海華,這是一個UIScrollView,使用自動佈局約束。

代碼

NSLayoutConstraint *makeWidthTheSameAsScrollView =[NSLayoutConstraint 
                 constraintWithItem:self.questionWebView 
                 attribute:NSLayoutAttributeWidth 
                 relatedBy:0 
                 toItem:self.masterScrollView 
                 attribute:NSLayoutAttributeWidth 
                 multiplier:1.0 
                 constant:0]; 

[self.view addConstraint:makeWidthTheSameAsScrollView]; 

NSLog(@"The width of questionWebView *AFTER* adding the constrain is: %f", self.questionWebView.frame.size.width); 
NSLog(@"The width of scrollView *AFTER* adding the constrain is: %f", self.masterScrollView.frame.size.width); 

當前結果

當我登錄的self.questionWebView(在UIWebView)的寬度,它的寬度在應用自動佈局約束時,不會改變。

問題

  • 這是正確的做法?
  • 我在做什麼錯?

P.S我知道這是對蘋果的建議放置UIWebViewUIScrollView,但是我已經關閉了滾動UIWebView使用屬性self.questionWebView.userInteractionEnabled = NO;的能力。目前使用UIWebView是我顯示HTML表格的最佳策略。

回答

16

根據要求改進Rob的答案。

正如Rob已經提到的,UIScrollViews在自動佈局下有特殊的行爲。

什麼是在這種情況下,有趣的是滾動視圖總寬度是通過使用它的子視圖總寬度確定的事實。所以,雖然scrollView已經問webView的寬度,你告訴webView也要求scrollView的寬度。這就是爲什麼它不起作用。一個人問另一個人,沒有人知道答案。你需要另一個參考視圖作爲web視圖的限制使用,然後滾動視圖也將能夠成功地詢問其預期的寬度。

一個簡單的方法可以這樣做:創造另一種觀點認爲,containerView,並添加滾動視圖作爲一個子視圖到。然後爲containerView設置適當的限制。比方說,你想集中於一個的viewController滾動視圖,對邊緣一些填充。因此,無論是對於containerView

NSDictionary *dict = NSDictionaryOfVariableBindings(containerView); 
[self.view addConstraints:[NSLayoutConstraints constraintsWithVisualFormat:@"H|-(100)-[containerView]-(100)-|" options:0 metrics:0 views:dict]; 
[self.view addConstraints:[NSLayoutConstraints constraintsWithVisualFormat:@"V|-(100)-[containerView]-(100)-|" options:0 metrics:0 views:dict]; 

然後你就可以繼續添加web視圖作爲一個子視圖的滾動視圖並設置其寬度:

NSLayoutConstraint *makeWidthTheSameAsScrollView =[NSLayoutConstraint 
                 constraintWithItem:self.questionWebView 
                 attribute:NSLayoutAttributeWidth 
                 relatedBy:0 
                 toItem:containerView 
                 attribute:NSLayoutAttributeWidth 
                 multiplier:1.0 
                 constant:0]; 

[self.view addConstraint:makeWidthTheSameAsScrollView]; 

這將使滾動型大和高大如webView,並且它們都將按照預期放置(對containerView設置約束)。

+1

您也可以在IB中執行此操作:https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AutoLayoutbyExample/AutoLayoutbyExample.html#//apple_ref/doc/uid/TP40010853-CH5-SW5 「在滾動視圖內創建錨定視圖」 – Brenden

3

Scrollviews在他們與自動佈局的交互方式上有點奇怪。請參閱TN2154(UIScrollView和Autolayout)。請參閱UIScrollView doesn't use autolayout constraints

一般來說,除了「當前滾動視圖的寬度」之外,您需要獲取包含視圖的寬度,因爲在自動佈局中,滾動視圖的寬度(即內容寬度)是根據其內容定義的。因此你目前的要求是循環的。

+2

一個簡單的策略是將scrollView作爲子視圖添加到另一個視圖中(如scrollView所示),並將Auto Layout設置爲使用此視圖的寬度來設置webView視圖。 –

+1

@AlohaSilver謝謝,請添加此作爲一個單獨的答案,我認爲這是有用的分解爲答案,而不是評論。 – drc