多标签&;CollectionView iOS中的ImageView
我计划制作一个像这样的collectionview,一行12列- 其中,在两个标签中,我要打印2个字符串,在它们之间将打印一个图像 我已经实现了两种数据源方法-多标签&;CollectionView iOS中的ImageView,ios,collectionview,Ios,Collectionview,我计划制作一个像这样的collectionview,一行12列- 其中,在两个标签中,我要打印2个字符串,在它们之间将打印一个图像 我已经实现了两种数据源方法- func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return collection.count } func collectionView(_ collectionV
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collection.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionview_cell", for: indexPath) as! CustomCollectionViewCell
cell.forecastHourlyTemp.text = "\(self.HourlyData[indexPath.row].temp)°C"
cell.forecastHourlyTime.text = self.HourlyData[indexPath.row].dt.fromUnixTimeToTime()
cell.forecastHourlyWeatherIcon.image = UIImage(named: self.HourlyData[indexPath.row].weather[0].icon)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 200)
}
但它只显示图像,而不是显示这三种图像-
在一些地方,人们仅使用图像/单个标签来演示collectionview。那么,是否可以在collectionview中一次显示3个视图项?在尝试以各种方式进行测试后,我发现问题在于高度。当collectionView的大小大于单元高度时,它将缩小并使其成为两列。因此,首先我将collectionView面积固定为单元格高度 我试图打印列表中不同数量的项目,比如1、2、3,然后突然发现了这个解决方案
最好在布局机制内调整集合项目的大小。因此,您可能需要创建一个自定义的
FlowLayout
,并将可用的数据除以3:
class WeatherCollectionViewFlowLayout: UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return assertionFailure("Collection view not found") }
let availableWidth = collectionView.bounds.width
let availableHeight = collectionView.bounds.height
let itemWidth: CGFloat = (availableWidth/3).rounded(.down)
itemSize = CGSize(width: itemWidth, height: availableHeight)
sectionInset = .zero
minimumLineSpacing = .zero
minimumInteritemSpacing = .zero
}
}
然后您应该将其作为collectionView
的布局传递
在故事板中:
或代码:
CollectionView(frame: frame, collectionViewLayout: WeatherCollectionViewFlowLayout())
所以不需要任何固定的宽度
一些注释
可用宽度
(或可用高度
)lowerCamelcase
,但类型除外:
return
关键字:let forecast = self.HourlyData[indexPath.row]
cell.forecastHourlyTemp.text = "\(forecast.temp)°C"
cell.forecastHourlyTime.text = forecast.dt.fromUnixTimeToTime()
cell.forecastHourlyWeatherIcon.image = UIImage(named: forecast.weather[0].icon)
HourlyData -> hourlyData
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { collection.count }