Ios 如何以编程方式创建和使用UIcollectionView?
我已经搜索了很多以编程方式创建Ios 如何以编程方式创建和使用UIcollectionView?,ios,iphone,uicollectionview,Ios,Iphone,Uicollectionview,我已经搜索了很多以编程方式创建UICollectionView,但没有一个建议使用它的最简单方法,即如何将标签或图像添加到UICollectionViewCell。大多数网站都建议UICollectionView的实现与UITableView相同,但主要区别在于我们尝试添加任何图像时。在UITableView中,我们可以在cellForRow方法中分配图像视图,其中cell==nil,并在(cell!=nil)中分配图像。但是在这里,对于UICollectionView ItemAtIndexP
UICollectionView
,但没有一个建议使用它的最简单方法,即如何将标签或图像添加到UICollectionViewCell
。大多数网站都建议UICollectionView
的实现与UITableView
相同,但主要区别在于我们尝试添加任何图像时。在UITableView
中,我们可以在cellForRow
方法中分配图像视图,其中cell==nil
,并在(cell!=nil
)中分配图像。但是在这里,对于UICollectionView ItemAtIndexPath
方法,不存在UITableView
的CellForRow
中的条件(cell==nil
)。因此,我们无法在itemAtIndexPath
方法中有效地分配UImageView
s或标签等变量。我想知道除了子类化UICollectionViewCell
并在该自定义类中分配变量之外,是否还有其他选择?任何人都可以提供帮助,非常感谢。在itemAtIndex方法中,没有其他方法可以创建或分配单元格。我们需要注册定制类以在定制类内创建任何视图。大概是这样的:
[UICollectionView registerClass:[CustomCollectionViewClass class] forCellWithReuseIdentifier:@"cellIdentifier"];
是我发现最有用的链接。希望它能帮助他人swift:
override func viewDidLoad() {
super.viewDidLoad()
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 70, height: 70)
let demoCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
demoCollectionView.dataSource = self
demoCollectionView.delegate = self
demoCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
demoCollectionView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(demoCollectionView)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 27
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
cell.backgroundColor = UIColor.lightGrayColor()
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
print("User tapped on item \(indexPath.row)")
}
也许这篇博文和我所做的相应github存储库在某种程度上帮助了你:是的,但我们必须在u建议的链接中对NSObject进行子类化。所以,要添加标签,除了子类化之外,没有其他方法,这在uitableview类中是不需要的。无论如何,谢谢你。