UIScrollView 滑動視圖


加入協定

class ViewController: UIViewController, UIScrollViewDelegate {

宣告資料

var scrollview = UIScrollView()
var label = UILabel()
let WIDTH = UIScreen.main.bounds.size.width
let HEIGHT = UIScreen.main.bounds.size.height

viewDidLoad

  • 背景顏色
    view.backgroundColor = .lightGray
    
  • UIScrollView
        // frame
        scrollview.frame = CGRect(x: 0, 
                                  y: 0, 
                                  width: WIDTH, 
                                  height: HEIGHT))
        // 內容範圍
        scrollview.contentSize = CGSize(width: WIDTH * 2, 
                                        height: HEIGHT * 2)
        // 起始點
        scrollview.contentOffset = CGPoint(x: 0, 
                                           y: 20)
        // 連接delegate
        scrollview.delegate = self
        // 水平指示器
        scrollview.showsHorizontalScrollIndicator = true
        // 垂直指示器
        scrollview.showsVerticalScrollIndicator = true
        // 指示器樣式
        scrollview.indicatorStyle = .default
        /*
        UIScrollViewIndicatorStyle
         .black       黑
         .white       白
         .default     預設
         */
        // 隱藏鍵盤
        //scrollview.keyboardDismissMode = .interactive
        /* 
        UIScrollViewKeyboardDismissMode
         .none            無動作
         .onDrag          滑動觸發
         .interactive     鍵盤預設高度內跟著滑動
         */
        // 點選狀態列跳至最上方
        scrollview.scrollsToTop = false
        // 可否滑動
        scrollview.isScrollEnabled = true
        // 鎖定滑動方向
        scrollview.isDirectionalLockEnabled = true
        // 以頁為單位滑動
        scrollview.isPagingEnabled = true
        // 彈回效果
        scrollview.bounces = true
        // 水平彈回效果
        //scrollview.alwaysBounceHorizontal = false
        // 垂直彈回效果
        //scrollview.alwaysBounceVertical = false
        // 縮放時彈回效果
        //scrollview.bouncesZoom = true
        // 預設縮放大小
        //scrollview.zoomScale = 1
        // 縮放最小
        //scrollview.minimumZoomScale = 1
        // 縮放最大
        //scrollview.maximumZoomScale = 1
    view.addSubview(scrollview)
    
  • UILabel(增加滑動視覺效果)
    for i in 0...1 {
        for j in 0...1 {
            let I = CGFloat(i)
            let J = CGFloat(j)
                label = UILabel(frame: CGRect(x: 0, 
                                              y: 0, 
                                              width: 200, 
                                              height: 100))
                label.center = CGPoint(x: (1 + 2 * I) * WIDTH / 2,
                                       y: (1 + 2 * J) * HEIGHT / 2)
                label.text = "( \(i) , \(j) )"
                label.textColor = .black
                label.textAlignment = .center
            scrollview.addSubview(label)
        }
    }
    

results matching ""

    No results matching ""