【发布时间】:2019-02-04 07:33:07
【问题描述】:
我正在尝试动态设置集合视图单元格的宽度。最初它没有按预期呈现。但是当我点击单元格时,它会根据我的需要进行调整。这是我写的代码:
代码
import UIKit
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
@IBOutlet weak var collView: UICollectionView!
var tasksArray = ["To Do", "SHOPPING","WORK"]
var selectedIndex = Int()
override func viewDidLoad() {
super.viewDidLoad()
let layout = collView?.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = UICollectionViewFlowLayout.automaticSize
layout.estimatedItemSize = CGSize(width: 93, height: 40)
// Do any additional setup after loading the view, typically from a nib.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tasksArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.lblName.text = tasksArray[indexPath.row]
if selectedIndex == indexPath.row
{
cell.backgroundColor = UIColor.lightGray
}
else
{
cell.backgroundColor = UIColor.white
}
cell.layer.borderWidth = 1
cell.layer.cornerRadius = cell.frame.height / 2
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndex = indexPath.row
self.collView.reloadData()
}
}
这里我附上两张点击前和点击后的图片,以便您轻松理解
[![这是我点击之前的图像
所以请告诉我我的代码有什么问题
【问题讨论】:
-
请适当添加图片。我编辑了您的问题以解释问题。
标签: ios swift uicollectionview uicollectionviewdelegateflowlayout