更改基于UITableViewCell Height的UICollectionView内容大小的高度

如何解决更改基于UITableViewCell Height的UICollectionView内容大小的高度

我正在使用UICollectionView创建的日历。

UICollectionView位于UITableViewCell内部 UITableViewCell方法heightForRowAt

中的return UITableView.automaticDimension

用于创建日历的UICollectionView会根据显示的天数来更新其高度,例如 11月的月份的第一天是星期日,因此要将日期置于标签“星期日” 下,collectionView必须添加整行。

通常每个月有5行(周),但是当每月的第一天发生在星期日时,collectionview 返回6

现在,正如我所说,我能够根据返回的行数来更新 UICollectionView 的高度,但是我无法动态更改{{1的 height }},其中包含TableViewCell

如何根据其中collectionView的高度调整tableViewCell的大小?


编辑

我的手机

enter image description here


我为包含CollectionView的单元格的高度设置了UITableView.automaticDimension

enter image description here

在类CalendarView中,我创建了一个变量CGFloat calendarH来设置collectionView的默认高度

enter image description here

CollectionView实施

enter image description here

我添加了一个观察者,它在CalendarView: UIView发生变化时跟踪其高度

enter image description here

我目前可以更改collctionView的高度,但是其超级视图(collectionView)和tableView单元格将继续保持固定的高度,并且无法适应bookingCalendarView

解决方法

您需要为集合视图的高度约束创建一个@IBOutlet

设置行的日历/月份数据时,确定需要5行还是6行。

如果为6,则将高度约束上的.constant设置为750

如果为5,则将高度约束上的.constant设置为675


修改

首先,我建议您不要使用“自动调整大小”集合视图。 UICollectionView旨在根据集合视图的大小来布置单元格 ,当单元格过多时可以自动滚动。

尝试“自我调整”大小 可能 在一个实例中有效,但在另一个实例中无效。在这种情况下失败的原因是因为您的表格视图布局了单元格,并在填充视图 之前计算了其高度,然后才可以“自行调整大小” 。”

相反,由于您知道单元格的高度为75,因此您可以计算日历需要多少行,并为集合视图的高度限制设置.constant,或者(因为您已经在使用heightForRowAt)计算那里的行高。

看下面的代码:

let dateComponents = DateComponents(year: year,month: month)
        
// startDate will be the first date of the month (Jan 1,Feb 1,Mar 1,etc...)
guard let startDate = calendar.date(from: dateComponents) else {
    fatalError("Something is wrong with the date!")
}
// get the range of days in the month
guard let range = calendar.range(of: .day,in: .month,for: startDate) else {
    fatalError("Something is wrong with the date!")
}
        
// get number of days in the month
let numberOfDaysInMonth = range.count
        
// get the day of the week for the first date in the month
//  this returns 1-based numbering
//  Nov 1,2020 was a Sunday,so this would return 1
let startDayOfWeek = Calendar.current.component(.weekday,from: startDate)
        
// add the "leading days to the start date"
//  so,if startDayOfWeek == 3 (Tuesday)
//  we need to add 2 "empty day cells" for Sunday and Monday
let totalCellsNeeded = numberOfDaysInMonth + (startDayOfWeek - 1)
        
// calculate number of rows needed -- this will be 4,5 or 6
//  the only time we get 4 is if Feb 1st in a non-leapYear falls on a Sunday
let numRows = Int(ceil(Double(totalCellsNeeded) / Double(7)))
        
// we now know the Height needed for the collection view
//  you said your calendar cell height is 75,so...
//  cvHeight = numRows * 75

我们可以将其循环放置,然后print()将信息override func viewDidLoad() { super.viewDidLoad() let calendar = Calendar.current // 2026 is the next year where Feb starts on a Sunday // so let's use that year to see that we get 4 rows for Feb let year = 2026 for month in 1...12 { let dateComponents = DateComponents(year: year,month: month) // startDate will be the first date of the month (Jan 1,etc...) guard let startDate = calendar.date(from: dateComponents) else { fatalError("Something is wrong with the date!") } // get the range of days in the month guard let range = calendar.range(of: .day,for: startDate) else { fatalError("Something is wrong with the date!") } // get number of days in the month let numberOfDaysInMonth = range.count // get the day of the week for the first date in the month // this returns 1-based numbering // Nov 1,so this would return 1 let startDayOfWeek = Calendar.current.component(.weekday,from: startDate) // add the "leading days to the start date" // so,if startDayOfWeek == 3 (Tuesday) // we need to add 2 "empty day cells" for Sunday and Monday let totalCellsNeeded = numberOfDaysInMonth + (startDayOfWeek - 1) // calculate number of rows needed -- this will be 4,5 or 6 // the only time we get 4 is if Feb 1st in a non-leapYear falls on a Sunday let numRows = Int(ceil(Double(totalCellsNeeded) / Double(7))) // we now know the Height needed for the collection view // you said your calendar cell height is 75,so... // cvHeight = numRows * 75 // debug output let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE" let dayName = dateFormatter.string(from: startDate) dateFormatter.dateFormat = "LLLL y" let dateString = dateFormatter.string(from: startDate) let dayPadded = dayName.padding(toLength: 10,withPad: " ",startingAt: 0) let datePadded = dateString.padding(toLength: 16,startingAt: 0) print("\(datePadded) has \(numberOfDaysInMonth) days,starting on \(dayPadded) requiring \(numRows) rows") } } 到调试控制台,如下所示:

January 2026     has 31 days,starting on Thursday   requiring 5 rows
February 2026    has 28 days,starting on Sunday     requiring 4 rows
March 2026       has 31 days,starting on Sunday     requiring 5 rows
April 2026       has 30 days,starting on Wednesday  requiring 5 rows
May 2026         has 31 days,starting on Friday     requiring 6 rows
June 2026        has 30 days,starting on Monday     requiring 5 rows
July 2026        has 31 days,starting on Wednesday  requiring 5 rows
August 2026      has 31 days,starting on Saturday   requiring 6 rows
September 2026   has 30 days,starting on Tuesday    requiring 5 rows
October 2026     has 31 days,starting on Thursday   requiring 5 rows
November 2026    has 30 days,starting on Sunday     requiring 5 rows
December 2026    has 31 days,starting on Tuesday    requiring 5 rows

这是输出:

cellForRowAt

所以...要么在

  • heightForRowAt ...计算所需的高度并在单元格中设置CV高度,或者
  • [[apim.throttling.url_group]] traffic_manager_urls = ["tcp://Traffic-Manager-host:9611"] traffic_manager_auth_urls = ["ssl://Traffic-Manager-host:9711"] [apim.throttling] service_url = "https://Traffic-Manager-host:${mgt.transport.https.port}/services/" throttle_decision_endpoints = ["tcp://Traffic-Manager-host:5672"] ...计算并返回该行所需的高度

侧面说明:建议您对所有单元格使用自动布局,而不要返回各种行高。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res