滚动时,我的按钮标签会堆叠/重新生成。因此,在离开视图并重新进入后,第一个标签可能会在其上方显示带有Elabel的Alabel。我只是尝试创建一行可滚动按钮(或标签)。集合视图和单元格是通过Storyboard创建的。代码在CV中生成正确数量的单元格,但滚动(水平)时标签变为分层。
let buttonLabels = ["Alabel", "Blabel", "Clabel", "Dlabel", "Elabel", "Flabel", "Glabel", "Hlabel", "Ilabel", "Jlabel", "Klabel", "Llabel", "Mlabel"]
@IBOutlet weak var btnCollVw: UICollectionView!
//loadColFlowLayout() is called from ViewDidLoad()
func loadColFlowLayout() {
let btnLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
btnLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
btnLayout.sectionInset = UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 1)
btnLayout.itemSize = CGSize(width: 63, height: 30)
btnCollVw.collectionViewLayout = btnLayout
btnCollVw!.backgroundColor = UIColor.whiteColor()
}
func numberOfSections() -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return buttonLabels.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell: UICollectionViewCell = self.iconCollVw.dequeueReusableCellWithReuseIdentifier("swIconsCell", forIndexPath: indexPath) as UICollectionViewCell
var makeButton = UIButton(frame: CGRectMake(0, 0, 63, 29))
makeButton.setTitle(buttonLabels[indexPath.item], forState: .Normal)
makeButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
cell.addSubview(makeButton)
// or using cell.contentView.addSubview(makeButton)
return cell
}
}
答案 0 :(得分:0)
单元格重用中的问题,每当你从集合视图中取出单元格时它已经有了按钮,当我检查单元格上已知标签的按钮时,请查看我的一些改进版本:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("swIconsCell", forIndexPath: indexPath) as UICollectionViewCell
if cell.viewWithTag(1234) == nil {
var makeButton = UIButton(frame: CGRectMake(0, 0, 63, 29))
makeButton.setTitle(buttonLabels[indexPath.item], forState: .Normal)
makeButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
makeButton.tag = 1234;
cell.addSubview(makeButton)
// or using cell.contentView.addSubview(makeButton)
}
return cell
}
你可以用另一种方式做同样的事情,例如创建UICollectionViewCell