我有一个集合视图,在集合视图单元格中我放置了一个UILabel。
这些是我想要分配给标签的值,因为将在视图中显示每个单元格:
let fibonacciSeries = ["0", "1", "2", "3", "5", "8", "13", "21", "34", "55", "89", "144", "∞", "☯"]
let myDeck = Card().createDeck(fibonacciSeries)
struct Card {
var name: String
func createDeck(deckType: [String]) -> [Card] {
var deck = [Card]()
for name in deckType {
deck.append(Card(name: name))
}
return deck
}
}
我得到了一个'无法转换类型' String'预期的论证类型' UIView'我尝试将值分配给标签时此函数出错:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CardCell
let value = myDeck[indexPath.row]
cell.addSubview(value.name) <----- error here
return cell
}
我想我真的明白它告诉我的是什么; cell.addSubview希望得到一个UIView,但我给它value.name(一个字符串)。我在这里发现了一些可能回答这个问题的帖子,但是他们已经在Objective-C中找到了我不了解的第一件事。例如:How to set UILabel on UICollectionViewCell?
我也试过这个:
...
let value = myDeck[indexPath.row].name <--- this didn't work
cell.addSubview(value)
return cell
}
非常感谢为这位初学者提供的任何帮助。
答案 0 :(得分:1)
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CardCell
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = myDeck[indexPath.row].name as! String
cell.addSubview(label)
return cell
}