4
4

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.

ViewControllerの外にViewを作成する(Swift)

Posted at

ViewControllerからViewの記述を排除する

言葉にしづらいのだけれど、ViewControllerにViewをドンドン追加していくと、Controllerがでかくなってしまうので、各々Viewは個別に記述したいと思った。

例えば、FirstViewControllerにUIWebViewを4個追加したいと思った時(思わないけど)、4つ追加するとViewController大変なことになるじゃないですか。
だからそれぞれのViewをControllerの外に持ったらControllerスッキリしていいよねって思った。

iOSネイティブ開発はじめたばかりで???ってなりながらやってるし、アンチパターン踏んでいたら教えて欲しいし、もっといい方法あったら知りたいです。

ViewController

画面サイズ決めて(frame1-4)、WebViewを1-4まで作って、表示する。


import UIKit

class FirstViewController: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()

        let frame1 = CGRect(x: 0, y: 0, width: self.view.bounds.width / 2, height: self.view.bounds.height / 2)
        let frame2 = CGRect(x: self.view.bounds.width / 2, y: 0, width: self.view.bounds.width / 2, height: self.view.bounds.height / 2)
        let frame3 = CGRect(x: 0, y: self.view.bounds.height / 2, width: self.view.bounds.width / 2, height: self.view.bounds.height / 2)
        let frame4 = CGRect(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2, width: self.view.bounds.width / 2, height: self.view.bounds.height / 2)


        let web1 = AppleWebView(frame:frame1)
        let web2 = AppleWebView(frame:frame2)
        let web3 = AppleWebView(frame:frame3)
        let web4 = AppleWebView(frame:frame4)


        self.view.addSubview(web1.createWebView())
        self.view.addSubview(web2.createWebView())
        self.view.addSubview(web3.createWebView())
        self.view.addSubview(web4.createWebView())
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

AppleWebView

import UIKit

class AppleWebView: UIWebView,UIWebViewDelegate {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.delegate = self
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func createWebView() -> UIWebView{
        let url: NSURL = NSURL(string: "http://apple.com")!
        let request: NSURLRequest = NSURLRequest(URL: url)
        self.loadRequest(request)

        return self
    }

    func webViewDidFinishLoad(webView: UIWebView!) {
        println("webViewDidFinishLoad")
    }

    func webViewDidStartLoad(webView: UIWebView!) {
        println("webViewDidStartLoad")
    }
}

画面

StatusBarとかNavigationBarの高さ考慮してないからか、画面崩れてる。

サイズ変更済みイメージ.png

「👿お前そのやり方はまずいよ…」とか、「😊もっといい方法ある」って場合は教えて下さい!

4
4
1

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?