iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 3
1
Software Development

Swift 新手上路之30天復刻版型系列 第 3

Day 3 - ASOS 滑動視圖

今天要來完成上半部的滑動視圖
https://ithelp.ithome.com.tw/upload/images/20171222/20107699U5UJDlnqZD.png

在這裡我們要新增三個元件:

  1. Image View
  2. Scroll View
  3. Page Control

Page Control與Scroll View要將階層拉出來到Image View之上,否則會被擋住
https://ithelp.ithome.com.tw/upload/images/20171222/20107699D8N5ClpyEn.png

利用Asistant editor建立三個元件的@IBOutlet

    @IBOutlet weak var myScrollView: UIScrollView!
    @IBOutlet weak var myImageView: UIImageView!
    @IBOutlet weak var myPageControl: UIPageControl!

將滑動視圖所用到的圖片加進Assets中,接下來處理程式碼的部分
一開始先建立一個放圖片的陣列

    var upperPics = ["1", "2", "3"]

接著在viewDidLoad中建立UIScrollView

override func viewDidLoad() {
        super.viewDidLoad()
        //實際可見視圖範圍寬度
        myScrollView.contentSize.width = (myScrollView.frame.width) * CGFloat(upperPics.count)
        //實際可見視圖範圍高度
        myScrollView.contentSize.height = 104
        //設置代理
        myScrollView.delegate = self
        //以每頁的方式進行更換
        myScrollView.isPagingEnabled = true
        //將超出部分會出現scroll bar的部分隱藏
        myScrollView.showsHorizontalScrollIndicator = false
        //custom page cotrol
        myPageControl.currentPageIndicatorTintColor = .black
        myPageControl.pageIndicatorTintColor = .gray
        //設定頁數
        myPageControl.numberOfPages = upperPics.count
        //起始頁
        myPageControl.currentPage = 0
    

將圖片顯示在myScrollView中

        for (index, pic) in upperPics.enumerated() {
            let image = UIImageView(image: UIImage(named: pic))
            image.contentMode = .scaleAspectFit
            image.frame = CGRect(x: CGFloat(index) * myScrollView.frame.width, y: 0, width: myScrollView.frame.width, height: myScrollView.frame.height)
            myScrollView.addSubview(image)   
        }

frame vs bounds
frame: 自已View相對於父View的座標位置和大小
bounds: 自已View local的座標位置和大小
圖片:https://upload-images.jianshu.io/upload_images/277755-217ccf2729acbf5c.png

接下來建立停止滑動後的代理方法來取得current page

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //update current page in page control while scrolling
        let currentPage = Int(myScrollView.contentOffset.x / myScrollView.frame.size.width)
        myPageControl.currentPage = currentPage


上一篇
Day 2 - ASOS 表格
下一篇
Day 4 - 麥當勞報報 版型檢視
系列文
Swift 新手上路之30天復刻版型30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言