新增日曆的功能
點選日期,可以讓區間內的Cell的顏色變成灰色
讓操作可以更直覺
在didselectItemat內
使用
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
條件列出:
變數:
條件選擇:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 作為點選的cell對象
selectItem = collectionView.cellForItem(at: indexPath)!
// 當前點選對象
var tap = indexPath.row
// 計算是否第一次參與 如果count = 1 那麼則是第一次參與
count += 1
if count == 1{
smalltap = tap
// 點選第一個cell變成灰色
selectItem.backgroundColor = UIColor.gray
}else
{
// 如果visited過了那麼就是已經有產生區間
if visted == false{
if tap < smalltap{
// 轉換tap與smalltap
store = smalltap
smalltap = tap
tap = store
// 計算總共幾天
day = tap - smalltap+1
// 讓目前區間都變成灰色
for i in smalltap...tap{
selectItem = collectionView.cellForItem(at: [0,i])!
selectItem.backgroundColor = UIColor.gray
}
count = 1
// 讓目前最大變成當前觸碰
bigtap = tap
// 讓textfield的文字變成 總共幾天累積
countDay.text = String(day)
}else
{
day = tap - smalltap+1
for i in smalltap...tap{
selectItem = collectionView.cellForItem(at: [0,i])!
selectItem.backgroundColor = UIColor.gray
}
count = 1
bigtap = tap
countDay.text = String(day)
}
// 有區間產生訊號產生
visted = true
// 在有區間產生的狀況下
}else
{
// 如果當前觸碰是比目前最小還要小的時候
if tap < smalltap{
store = smalltap
smalltap = tap
tap = store
day = tap - smalltap+1
// 讓 目前最小到當前觸碰都變成灰色
for i in smalltap...tap{
selectItem = collectionView.cellForItem(at: [0,i])!
selectItem.backgroundColor = UIColor.gray
}
// 讓 當前觸碰到目前最大顏色都變不見
for i in tap+1...bigtap{
selectItem = collectionView.cellForItem(at: [0,i])!
selectItem.backgroundColor = .clear
}
bigtap = tap
countDay.text = String(day)
count = 1
// 如果當前觸碰比目前最大還要大的時候
}else if (tap > bigtap)
{
store = bigtap
bigtap = tap
tap = store
day = bigtap - tap + 1
for i in tap...bigtap{
selectItem = collectionView.cellForItem(at: [0,i])!
selectItem.backgroundColor = UIColor.gray
}
for i in smalltap...tap-1{
selectItem = collectionView.cellForItem(at: [0,i])!
selectItem.backgroundColor = .clear
}
smalltap = tap
countDay.text = String(day)
count = 1
// 如果當前觸碰介於目前最大跟目前最小之間
}else if (smalltap < tap) && (tap < bigtap)
{
day = tap - smalltap + 1
// 讓目前最小到當前觸碰的區間變成灰色
for i in smalltap...tap{
selectItem = collectionView.cellForItem(at: [0,i])!
selectItem.backgroundColor = UIColor.gray
}
// 讓當前觸碰到目前最大的區間的顏色變不見
for i in tap+1...bigtap{
selectItem = collectionView.cellForItem(at: [0,i])!
selectItem.backgroundColor = .clear
}
countDay.text = String(day)
bigtap = tap
count = 1
}
}
}
}
成果展示: