Swift 如何获取 collectionView 中的中心单元格并在滚动时调整其大小?

2023-12-09

I have a horizontal collectionView and i would like to manage that when scrolling it, the centre cell becomes larger. So, each time a cell is the center cell it will be larger than the others. Check the image beneath. enter image description here

谁能帮助我找到最好的方法来做到这一点?提前致谢!

到目前为止我的代码:

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource,      UICollectionViewDelegate {
@IBOutlet var horizontalCollectionView: UICollectionView!
@IBOutlet var verticalCollectionView: UICollectionView!

var horizontal = ["1","2","3","4","5","6","7","8","9","10","1","2","3","4","5","6","7","8","9","10"]
var horizontalCellSize = CGSize(width: 50, height: 50)
var horizontalLargeCellSize = CGSize(width: 80, height: 80)


var centerCell = UICollectionViewCell()
var cellIsInCenter = false
var myIndexPath = IndexPath()

override func viewDidLoad() {
    super.viewDidLoad()

}

// When the main view's dimensions change this will re-layout the collection view
override func viewWillLayoutSubviews() {
    verticalCollectionView.collectionViewLayout.invalidateLayout()
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return horizontal.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == horizontalCollectionView {
        let horizontalCell = collectionView.dequeueReusableCell(withReuseIdentifier: "HorizontalCell", for: indexPath) as! HorizontalCell
        horizontalCell.backgroundColor = UIColor.blue
        horizontalCell.textLabel.text = horizontal[indexPath.row]
        return horizontalCell
    }

   else {

        let verticalCell = collectionView.dequeueReusableCell(withReuseIdentifier: "VerticalCell", for: indexPath) as! VerticalCell
        verticalCell.backgroundColor = UIColor.red
        verticalCell.textLabel.text = horizontal[indexPath.row]
        return verticalCell
    }
}

// MARK: UIScrollViewDelegate

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == self.horizontalCollectionView {
        let horizontalScrollPosition = scrollView.contentOffset.x * 35
        self.verticalCollectionView.delegate = nil
        self.verticalCollectionView.contentOffset = CGPoint(x: 0, y: horizontalScrollPosition)
        self.verticalCollectionView.delegate = self
    }

    if scrollView == self.verticalCollectionView {
        let verticalScrollPosition = scrollView.contentOffset.y
        self.horizontalCollectionView.delegate = nil
        self.horizontalCollectionView.contentOffset = CGPoint(x: verticalScrollPosition, y: 0)
        self.horizontalCollectionView.delegate = self 
    }
}


// MARK: CollectionViewLayout

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if collectionView == verticalCollectionView {
        let size = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height)

        return size
    }

    if indexPath.item == 3 {
        return CGSize(width: 70, height: 70)
    }
    return CGSize(width: 50, height: 50)

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    self.verticalCollectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
    print("\(indexPath)")
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    var closestCell: UICollectionViewCell = self.horizontalCollectionView.visibleCells[0]
    for cell in self.horizontalCollectionView.visibleCells as [UICollectionViewCell] {
        let closestCellDelta = abs(closestCell.center.x - self.horizontalCollectionView.bounds.size.width / 2.0 - self.horizontalCollectionView.contentOffset.x)
        let cellDelta = abs(cell.center.x - self.horizontalCollectionView.bounds.size.width/2.0 - self.horizontalCollectionView.contentOffset.x)
        if (cellDelta < closestCellDelta){
            closestCell = cell
            self.centerCell = cell
            self.cellIsInCenter = true
            horizontalCellSize = CGSize(width: 80, height: 50)
        }
    }
    let indexPath = self.horizontalCollectionView.indexPath(for: closestCell)
    self.horizontalCollectionView.scrollToItem(at: indexPath!, at: .centeredHorizontally , animated: true)
    if closestCell.backgroundColor == UIColor.black {
        closestCell.backgroundColor = UIColor.blue
    }
    horizontalCollectionView.reloadItems(at: [self.horizontalCollectionView.indexPath(for: closestCell)!])
    closestCell.backgroundColor = UIColor.black
}
}

试试这个:

func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if collectionView == verticalCollectionView {
let size = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height)
        return size
    }
let point = CGPoint(x: self.view.frame.size.width/2.0, y:35 )
//or you can try this code also
//let point = CGPoint(x: UIScreen.main.bounds.width/2, y:35 )
    print(point)
let centerIndex = self.collectionView.indexPathForItemAtPoint(point)
    if indexPath.item == centerIndex {
        return CGSize(width: 70, height: 70)
    }
    return CGSize(width: 50, height: 50)
}

此代码为您提供集合视图中心的项目的索引。 希望这可以帮助

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift 如何获取 collectionView 中的中心单元格并在滚动时调整其大小? 的相关文章

随机推荐

  • mfc 复制 CString 的某些部分

    假设我有一个 CString 变量 其中包含字符串 Bob Evans 我想从位置 4 直到原始 CString 的末尾复制到新的 CString 但我无法找到为此的语义示例 CString original Bob Evans Below
  • 如何通过ngrok访问子域?

    我有一个带有 api 子域的 Rails 站点 我本地机器上的路由如下所示 http mysite dev lt normal web stuff http api mysite dev lt my api 如何映射这两个子域 这是我的 n
  • C++ 打印模板容器错误(错误:'operator<<' 的重载不明确)理解吗?

    我想编写可以打印容器的模板函数std vector std 列表 下面是我的函数 只是重载 lt lt template
  • 使用ajax将表单数据发送到php

    我想将表单数据从ajax发送到php 我的 ajax 检索表单数据 但它没有发送它 我没有看到代码有任何问题 也许我需要更专业的帮助 提前致谢 HTML5语法 div align center a Header a div a Sign I
  • 尝试在 python 中发布多部分表单数据,不会发布

    我对 python 相当陌生 所以如果我错过了一些简单的事情 我提前道歉 我正在尝试将数据发布到 python 中的多部分表单 脚本运行 但不会发布 我不确定我做错了什么 import urllib urllib2 from poster
  • 未找到接口“JsonSerialized”

    我正进入 状态Interface JsonSerializable not found error在我的网站上 我在用Laravel 5 4 and PHP 7 1 13 JSON module也启用于Cpanel 但我仍然收到以下错误 P
  • 想要使用 C# 将单词的几个字符加粗在 winforms 的树节点中加粗

    我有 搜索文本框 可以在树视图中搜索 我给出的结果很好 但我想让这些部分变得粗体 我在 winform 的 搜索文本框 中输入了这些部分 例如 我输入 Ram 然后它给出 Ram esh TreeNode 类不支持这一点 它的 Text 始
  • 如何从结果集中获取日期

    从 ResultSet 获取 Date 对象时遇到问题 在数据库中它有一个值 例如2014 08 01 从resultSet中获取它后 它有另一个值 2014 08 31 我知道 ResultSet 的 getDate 方法返回 java
  • 在 appengine 中使用较少的数据存储小操作

    我正在使用 python 27 在 appengine 上制作一个基本相册 我编写了以下方法来从与特定 冒险 匹配的数据存储中检索图像详细信息 我使用限制和偏移量进行分页 但效率非常低 浏览 5 个页面 每页 5 张照片 后 我已经使用了
  • 防止数据库中出现重复值 - mysql

    我有一个表存储有关某些事件重复发生的值 例如 事件id 1发生在周一 周三和周五 并且该活动与id 2发生在周一和周三 所以我的表是这样的 id event id day 1 1 Monday 2 1 Wednesday 3 1 Frida
  • 使用 Java 的回文测试器,忽略空格和标点符号

    我已经编写了程序 直到它必须忽略线程中的标点符号和空格 我想知道是否有人可以帮助我编码 我一直在尝试的似乎不起作用 这是我到目前为止所拥有的 import java util Scanner public class PalindromeT
  • 验证失败时禁用保存按钮

    正如您从标题中可以看到的 我要问的问题以前已经被问过很多次了 但是 在阅读了所有这些其他问题之后 我仍然找不到解决我的问题的合适方法 我有一个具有基本验证的模型类 partial class Player IDataErrorInfo pu
  • 布局管理器在 java 中设置此特定布局

    我有这个布局 我需要为作业进行编程 这是我第一次在 GUI 中使用布局管理器 所以我在使布局匹配时遇到问题 我需要你的帮助 我有两个标签为 帐户创建 和 帐户转移 的选项卡 这些都可以 我需要的是将 JLabel 帐户 ID 和第一个文本字
  • 在 Swing 的 JTextPane 中设置选项卡策略

    我希望 JTextPane 在按下 Tab 时插入空格 目前它插入制表符 ASCII 9 无论如何 是否可以自定义 JTextPane 的选项卡策略 除了捕获 选项卡键 事件并自己插入空格似乎是一个 您可以在 JTextPane 上设置 j
  • 如何将R中矩阵的列(累加和)相加?

    我有一个关于将矩阵的列相加的问题 例如 I have a matrix 1 2 3 1 1 3 1 2 2 4 2 I want it to be 1 2 3 1 1 4 5 2 2 6 8 我们可以申请cumsum在每一行上通过循环遍历行
  • 可以将python中的bz2解压到文件而不是内存中

    我曾经使用过在内存中解压和读取文件bz2图书馆 但是 我已通读文档 似乎不能只是简单地解压缩文件 以在文件系统上使用解压缩的数据创建一个全新的文件 而无需内存存储 当然 您可以使用 BZ2Decompressor 逐行读取 然后将其写入文件
  • 如何使用 Traceit 报告堆栈跟踪中的函数输入变量

    我一直在使用以下代码来跟踪程序的执行 import sys import linecache import random def traceit frame event arg if event line lineno frame f li
  • 在 StreamBuilder 中使用 AnimatedList

    我正在使用 firebase 构建一个聊天应用程序 目前将每条消息作为文档存储在 firebase 的集合中 我使用 StreamBuilder 来获取最新消息并显示它们 我想在接收和发送新消息时添加动画 我尝试过使用 Animatedli
  • Pip 没有安装我的个人应用程序的最新依赖项

    您好 我有一个个人 pip 存储库 其中上传了 3 个版本的个人库 版本是 my lib 0 1 0 my lib 1 0 0 my lib 1 0 1 我有另一个应用程序 它使用 my lib 作为依赖项 在setup py文件如 ins
  • Swift 如何获取 collectionView 中的中心单元格并在滚动时调整其大小?

    I have a horizontal collectionView and i would like to manage that when scrolling it the centre cell becomes larger So e