19
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WKWebviewを使って、ネイティブ部分とHTMLを同居させて、画像をバインバインさせてみる。

Last updated at Posted at 2016-07-01

こんな感じにバインバインさせてみたかった。よく見ますよね、こういうアプリ。

7月-01-2016-11-38-53-compressor.gif

WKWebViewベースで、画像はネイティブ部分に置いて、UIScrollViewDelegateの変化度で反応させます。

コードはこんな感じです。
ポイントは、

  • webView.scrollView.backgroundColorを透明にすること
  • webView.scrollView.contentInsetでcontent部分をズラすこと

かな。

import UIKit
import WebKit

class ViewController: UIViewController, UIScrollViewDelegate {

    var webView = WKWebView()
    let topMargin : CGFloat = 300
    let sampleImg = UIImageView(image: UIImage(named: "sample"))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
        webView.scrollView.backgroundColor = UIColor.clearColor()
        webView.scrollView.contentInset.top = topMargin
        webView.scrollView.delegate = self
        
        self.view.addSubview(sampleImg)
        self.view.addSubview(webView)
        
        let fileName: String = "template"
        let filePath: String = NSBundle.mainBundle().pathForResource(fileName, ofType: "html")!
        let text = try! String(contentsOfFile: filePath)
        webView.loadHTMLString(text, baseURL: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let movingDiff = (scrollView.bounds.origin.y + topMargin) * -1
        print(movingDiff)
        if movingDiff > 0 {
            let retio = 1 + (movingDiff / 100);
            sampleImg.transform  = CGAffineTransformMakeScale(retio, retio);
        }
    }

}
19
21
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
19
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?