获取 UIScrollView contentView 的高度
Posted
技术标签:
【中文标题】获取 UIScrollView contentView 的高度【英文标题】:get height of UIScrollView contentView 【发布时间】:2016-04-02 01:11:24 【问题描述】:我有一个UIViewController
,它具有以下层次结构(及其NSLayoutConstraint
s):
UIView
-UIScrollView
--UIView-ContentView (zero margins to the UIScrollview and equal height to UIScrollVIew's parent; mentioned in the code as self.contentView)
---UIView (fixed height, 0 top margin to Content View)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIWebView (fixed height & linked to IBOutlet in the class; gets expanded)
---UILabel (top margin to UIWebView)
---UIView (fixed height, top margin to above label)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIButton (fixed height, top margin to above view)
Scenario:
1. On viewDidLoad() I'm adding the html text by appending the javascript code that returns the height of the UIWebView
2. on UIWebViewDelegate method (shouldStartLoadWithRequest) I'm setting the following things:
- webViewHeight.constant (NSLayoutConstraint, linked from IB)
- self.scrollView.contentSize = CGSizeMake(self.view.frame.width, CGRectGetHeight(self.contentView.frame))
override func viewDidLoad()
self.webView.scrollView.scrollEnabled = false
let heightHackScript = "<script type='text/javascript'>window.onload = function() window.location.href = 'ready://' + document.body.offsetHeight; </script>"
if let cBody:NSData = self.model?.text_content
self.webView.loadHTMLString(heightHackScript + String(data: cBody, encoding: NSUTF8StringEncoding)!, baseURL: nil)
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
let url = request.URL
if navigationType == .Other
if url?.scheme == "ready"
webViewHeight.constant = (url?.host?.floatValue)!
self.scrollView.contentSize = CGSizeMake(self.view.frame.width, CGRectGetHeight(self.contentView.frame))
return false
return true
问题是CGRectGetHeight(self.contentView.frame)
没有获得所需的高度。有什么想法吗?
所以我想在将 HTML 加载到 UIWebView 后获得视图约束的高度。
【问题讨论】:
【参考方案1】:尝试调整 Web 视图的大小以适应其内容时遇到的难题是,Web 视图本身并不知道其中显示的 DOM 内容可能有多高。你要做的就是通过 JavaScript 询问 DOM 它的内容有多高。在我们的代码中,我们这样做:
[webView stringByEvaluatingJavaScriptFromString: @"document.height"]
或在 Swift 中:
webView.stringByEvaluatingJavaScriptFromString("document.height")
并使用结果值为我们的 UIWebView 选择大小。
【讨论】:
谢谢,但我想得到的是UIView-ContentView (zero margins to the UIScrollview and equal height to UIScrollVIew's parent; mentioned in the code as self.contentView)
的总高度,根据这个高度我会更新 UIScrollView 的高度 ContentSize。以上是关于获取 UIScrollView contentView 的高度的主要内容,如果未能解决你的问题,请参考以下文章
在 UIScrollView 中获取 UIImage 可见部分的正确坐标
使用 `UIScrollView` 获取 `UITableViewCell` indexPath
在动画之前获取两个 CGPoint 之间的值(uiscrollview)