我建议的想法是在collectionView 中使用tableView。要遵循的步骤-:
1) 在您的控制器上添加 segmentedControl 和 collectionView。
2) 通过将控件从collectionView 拖动到控制器yello 图标来连接dataSource 和delegate。
3) 调整您的cell 高度。
4) 选择collectionView,然后转到属性检查器。寻找-:1) 滚动方向 并使水平。 2) 检查Paging Enabled参数。
5) 在views 上应用Constraints。
6) 给出collectionView 单元标识符。
7) 给你的cell 一个自定义的collectionView 单元类。
8) 将所有Outlets 连接到受尊重的views。
控制器类-:
import UIKit
class ViewController: UIViewController {
// OUTLETS
@IBOutlet weak var controls: UISegmentedControl!
@IBOutlet weak var horizontalCollectionView: UICollectionView!
// ARRAy OF TYPE UICOLOR
var collectionViewColors = [UIColor.gray,UIColor.green,UIColor.red,UIColor.yellow,UIColor.blue,UIColor.brown]
// ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
}
//didReceiveMemoryWarning
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Function to calculate cell index on scroll end.
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>){
let pagingIndex = targetContentOffset.pointee.x/self.view.frame.width
// Set segmented controll current index
controls.selectedSegmentIndex = Int(pagingIndex)
}
}
// Collection view methods
extension ViewController : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
// number of section
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
// number of items in section
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionViewColors.count
}
// deque cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection", for: indexPath) as! HorizontalCell
cell.horizonatlColorsView.backgroundColor = collectionViewColors[indexPath.item]
return cell
}
// set minimum line spacing to zero.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
自定义单元格类-:
import UIKit
class HorizontalCell: UICollectionViewCell {
// UIView outlet
@IBOutlet weak var horizonatlColorsView: UIView!
}
设置好一切后,水平滚动你会得到你想要的输出。你也可以在collectionView里面添加tableView。
输出-: