我的视图控制器有一个带有 6 个按钮/段的 UISegmentedControl。它在该分段控件下还有一个 UITableView。如果我们通过单击切换段,则表视图将重新加载不同的数据。现在我们正在尝试实现一种方法,如果用户从左到右或从右到左滑动表格视图,视图控制器中将出现类似分页的行为。
表示表格视图将随着分段控件水平滚动。我们如何以最佳方式在我的应用程序中实现此功能?我的表格有三个不同的自定义单元格,其中一个单元格内还有一个 UICollectionView。
我建议的想法是在
tableView
中使用 collectionView
。遵循的步骤-:
1) 在控制器上添加
segmentedControl
和 collectionView
。
2) 通过控制从
dataSource
拖动到控制器yello图标来连接
delegate
和collectionView
。
3) 调整你的
cell
高度。
4) 选择
collectionView
,然后转到属性检查器。寻找-:1) 滚动方向并使水平。 2) 检查Paging Enabled
参数。
5) 将
Constraints
涂在views
上。
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!
}
设置完所有内容后,水平滚动您将获得您想要的输出。您现在也可以在
tableView
内添加 collectionView
。
输出-: