我想问一下。我从 collectionView 制作了一个自定义菜单栏,我想在滑动时链接并更改我的收藏 View 菜单栏和另一个 collectionView 的数据。这是我正在尝试制作的图片
但是当尝试向左和向右滑动时我的菜单栏没有跟随,我已经做了一个引用来捕获值。但它仍然不起作用。这是我的代码
class SegmentedView: UIView {
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
return cv
}()
let knowledge = ["Pengetahuan", "Keterampilan", "Sikap"]
var selectedMenu: CGFloat?
}
extension SegmentedView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return knowledge.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! SegmentedCell
let item = knowledge[indexPath.item]
cell.nameLabel.text = item
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedMenu = CGFloat(indexPath.item) * frame.width
}
}
// This from my SegmentedViewController
class SegmentedViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var segmentedViews: SegmentedView!
let cellId = "assesmentCell"
let colors: [UIColor] = [UIColor.blue, UIColor.yellow, UIColor.green]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupCollection()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print(scrollView.contentOffset.x / 3)
segmentedViews.selectedMenu = scrollView.contentOffset.x / 3
}
func setupCollection() {
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
}
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.isPagingEnabled = true
}
}
谢谢。
最佳答案
您的 selectedMenu 属性不监听带有 didSet property observer 的事件.所以当你在 scrollViewDidScroll 中设置 selectedMenu 时,没有任何反应。
这可能是一个解决方案:
var selectedMenu: CGFloat? {
didSet {
collectionView.selectItem(at: <#T##IndexPath?#>, animated: <#T##Bool#>, scrollPosition: <#T##UICollectionView.ScrollPosition#>)
}
}
但是要小心 SegmentedView 的 collectionView(_:didSelectItemAt:) 方法,它会带来一些不需要的行为。您可以使用委托(delegate)模式来触发另一个类中的方法。
关于ios - 带有 Collection View 的自定义菜单栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59808182/