我的 View Controller 有一个带有 6 个按钮/段的 UISegmentedControll。它在分段控件下还有一个 UITableView。如果我们通过单击切换段,则 TableView 将重新加载不同的数据。现在我们正在尝试实现一种方法,如果用户从左到右或从右到左滑动表格 View , View Controller 中将出现类似分页的行为。意味着表格 View 将随着分段控件水平滚动。我们如何以最佳方式在我的应用程序中实现此功能?我的表格有三个不同的自定义单元格,其中一个单元格内还有一个 UICollectionView。请帮助我。谢谢。
最佳答案
我建议的想法是在collectionView
中使用tableView
。遵循的步骤-:
1) 在 Controller 上添加 segmentedControl
和 collectionView
。
2) 通过将控件从 collectionView
拖动到 Controller yello 图标来连接 dataSource
和 delegate
。
3) 调整单元格
高度。
4) 选择collectionView
,然后转到属性检查器。寻找-:1) 滚动方向并设为水平。 2) 检查Paging Enabled
参数。
5) 对 View
应用约束
。
6) 给出collectionView
单元格标识符。
7) 为您的cell
提供一个自定义collectionView
单元类。
8) 将所有Outlet
连接到受尊重的 View
。
Controller 类-:
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
。
输出-:
关于ios - 如何使用 UITableView 和分段控件进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47374321/