类似朋友圈九宫格布局,一张,两张,四张等情况时,用imageView来添加,约束非常繁琐,现在有一种简单的布局方法:collectionView,然后根据图片个数,来定义collectionView的layout和collectionView的高度:
var images = [String](){
didSet{
if images.count == 0 {
imageBackViewHeight.constant = 0
}
if images.count == 1 {
let height = screenwidth - 30
imageBackViewHeight.constant = height
collectionLayout.itemSize = CGSize(width: height, height: height)
collectionLayout.minimumLineSpacing = 0
collectionLayout.minimumInteritemSpacing = 0
}
if images.count == 2 {
let height = (screenwidth - 3 - 30)/2
imageBackViewHeight.constant = height
collectionLayout.itemSize = CGSize(width: height, height: height)
collectionLayout.minimumLineSpacing = 0
collectionLayout.minimumInteritemSpacing = 3
}
if images.count == 3 {
let height = (screenwidth - 6 - 30)/3
imageBackViewHeight.constant = height
collectionLayout.itemSize = CGSize(width: height, height: height)
collectionLayout.minimumLineSpacing = 0
collectionLayout.minimumInteritemSpacing = 3
}
if images.count == 4 {
let height = (screenwidth - 6 - 30)/2
imageBackViewHeight.constant = height * 2 + 3
collectionLayout.itemSize = CGSize(width: height, height: height)
collectionLayout.minimumLineSpacing = 3
collectionLayout.minimumInteritemSpacing = 3
}
if images.count > 4 && images.count < 7 {
let height = (screenwidth - 6 - 30)/3
imageBackViewHeight.constant = height * 2 + 3
collectionLayout.itemSize = CGSize(width: height, height: height)
collectionLayout.minimumLineSpacing = 3
collectionLayout.minimumInteritemSpacing = 3
}
if images.count >= 7 {
let height = (screenwidth - 6 - 30)/3
imageBackViewHeight.constant = height * 3 + 6
collectionLayout.itemSize = CGSize(width: height, height: height)
collectionLayout.minimumLineSpacing = 3
collectionLayout.minimumInteritemSpacing = 3
}
collectionView.reloadData()
}
}
然后利用回调,把想要的数据回调过来,比如点击图片放大什么的:
//cell里的collectionView
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let tapImageBlock = self.tapImageBlock{
tapImageBlock(indexPath.item, self.images[indexPath.item])
}
}
//列表的tableview代理
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "QLHomeTrendsCell", for: indexPath) as! QLHomeTrendsCell
cell.images = self.dataArr[indexPath.row]
cell.tapImageBlock = {(index, imageUrl) in
print("点击了第\(index)张图片,图片链接是\(imageUrl)")
}
return cell
}
网友评论