UIScrollView - ドラッグで画面をスクロール

f:id:oynop:20150226005722p:plain:h300 f:id:oynop:20150226005822p:plain:h300 f:id:oynop:20150226005827p:plain:h300

説明

UIScrollViewはUIViewのサブクラスで,UITextView, UITableView, UICollectionViewのスーパークラスになっています.

ソースコード

UIScrollViewSample.swift

import UIKit
class UIScrollViewSample: UIView, UIScrollViewDelegate {
    let panel: UIView!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        panel = UIView(frame: CGRectMake(20, 20, self.frame.width - 40, self.frame.height * 1.5 - 40))
        panel.backgroundColor = colorPattern.back()
        let label = UILabel(frame: CGRectMake(0, 0, 200, 40))
        panel.addSubview(label)

        label.center = panel.center
        label.textAlignment = NSTextAlignment.Center
        label.text = "UIScrollViewSample"
        label.textColor = colorPattern.lightText()
        label.backgroundColor = colorPattern.main()
        
        let sv = UIScrollView(frame: self.frame)
        self.addSubview(sv)
        
        // 内容を追加
        sv.addSubview(panel)
        
        // スクロール可能領域のサイズ
        sv.contentSize = CGSizeMake(panel.frame.maxX + 20, panel.frame.maxY + 20)
        
        // デリゲートを指定
        sv.delegate = self

        // 背景色を指定
        sv.backgroundColor = colorPattern.accent()

        // 拡大・縮小の範囲
        sv.minimumZoomScale = 0.2
        sv.maximumZoomScale = 2.0

        // 水平・鉛直方向へバウンドさせる (デフォルトでははみ出ている時のみバウンド)
        sv.alwaysBounceHorizontal = true
        sv.alwaysBounceVertical = true
    }
    // 拡大・縮小
    func viewForZoomingInScrollView(sv: UIScrollView) -> UIView {
        return panel
    }
    // 拡大後に中心を合わせる (デフォルトではpanelは左上に寄っている)
    func scrollViewDidZoom(sv: UIScrollView) {
        if panel.frame.width < sv.frame.width {
            panel.center.x = sv.center.x
        } else {
            panel.frame.origin.x = 0
        }
        if panel.frame.height < sv.frame.height {
            panel.center.y = sv.center.y
        } else {
            panel.frame.origin.y = 0
        }
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

ViewController.swift

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {       
        super.viewDidLoad()
        self.view.backgroundColor = colorPattern.back()
        self.view.addSubview(UIScrollViewSample(frame: self.view.frame))
    }
   
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}