LoginSignup
7
6

More than 5 years have passed since last update.

UIWebViewの高さを動的に変更する方法

Posted at

UIWebViewで動的に高さを変更したかった。
※ちなみにRubyMotion使ってますが、やり方はそんな変わらないはず。

調べるとwebViewDidFinishLoad内でJSでコンテンツの高さを取得して設定する方法が一般的らしい。
ということで試してみたら出来ずに困った。
まず最初はこんな感じで書いてみた。

view_controller.rb
def viewDidLoad
  super
  web_view=UIWebView.alloc.initWithFrame(self.view.frame)
  web_view.delegate =self
  web_view.loadHTMLString("<html><body>text</body></html>", baseURL: nil)
  self.view.addSubview web_view
end

def webViewDidFinishLoad(web_view)
  height = web_view.stringByEvaluatingJavaScriptFromString("document.documentElement.clientHeight;")
  new_bounds = web_view.bounds
  new_bounds.size.height=height.floatValue
  web_view.frame=new_bounds
end

でも高さが変わらない。
heightの値を見るとWebViewの高さがそのまま返ってきてる模様。
でもコンテンツの高さなんて「text」しか書いてないのでそんなわけない。

結果JSで取得する方法を変えてみたら取得できた。
単にJSの問題・・・。

view_controller.rb
def viewDidLoad
  ()
  web_view.loadHTMLString("<html><body><div id='HtmlId'>text</div></body></html>", baseURL: nil)
  self.view.addSubview web_view
end

def webViewDidFinishLoad(web_view)
  height = web_view.stringByEvaluatingJavaScriptFromString("document.getElementById('HtmlId').clientHeight;")
  ()
end

でもUIWebViewの大きさを動的に変更したあとの数値を使って画面を構成しようと思ったらwebViewDidFinishLoadのあとに処理書くことになるのかな?
うーむイマイチ理解不足。。。

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6