iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 23
0
Software Development

Swift零基礎實作旅遊景點app系列 第 23

Swift-Day23:旅遊App中利用CollectionView中的Item來進行ScrollView的控制練習

  • 分享至 

  • twitterImage
  •  

分類: UIKit學習

1. 前言:

在昨天的練習中,成功實現了以ScrollView來切換整個TableView,現在要嘗試在上面新增一個橫向的CollectionView,點擊上面的Cell,可以來切換下面的ScrollView,這個概念是參考“旅魔人”這個app來練習。

2. 實作:

有兩個方法,一個是用didSelectItem內建的方法;另一個是用Protocol的方法。
2-1. 方法1:
在上方新增一個CollectionView,在裡面的Cell裡面新增標籤,蓋住整個Cell,然後實作didSelectItem,這邊有一點需要很注意,千萬不要把Button蓋在Cell上面(方法2用protocol的方式可以,但此法不行),因為這樣會讀不到點按Cell的事件,他偵測到的反而會是button的點按事件,didSelectItem方法會失效讀不到,自己卡關很久才發現原因,程式碼如下,其他部分請參考Day22。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == 0{
            print("0")
            myScrollView.setContentOffset(CGPoint(x: 0, y: 0) , animated: true)
        }else{
            print("other item")
            myScrollView.setContentOffset(CGPoint(x: self.view.frame.width, y: 0), animated: true)
        }
    }

2-2. 方法2:
用protocol的方式請參考day 21,只是把tableView改成collectionView。

結果如下:


上一篇
Swift-Day22: 旅遊App中的TableView可以向左滑動實作練習
下一篇
Swift-Day24:旅遊app實作遭遇許多bug
系列文
Swift零基礎實作旅遊景點app30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言