ios - 如何更改 UICollectionViewCell 中 UILabel 的值?

标签 ios swift uicollectionview uicollectionviewcell

我有一个 Collection View ,在 Collection View 单元格中我放置了一个 UILabel。

这些是我要在创建将出现在 View 中的每个单元格时分配给标签的值:

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
}

非常感谢对这个初学者的任何帮助。

最佳答案

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
}

关于ios - 如何更改 UICollectionViewCell 中 UILabel 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36513920/

相关文章:

ios - 在 Swift 中设置 NSManagedObject 关系

swift - 在 tvOS 上的 SwiftUI 中更改按钮的颜色

ios - Xcode 6 : How to make an image view fill the screen on all devices? 自动布局不起作用?

swift - 判断拖动单元格路径是否==节头路径

ios - UICollectionView 滚动更改选定的单元格

swift - 为什么我的收藏 View 单元格颜色选择不起作用

iphone - UINavigationController inside UIViewController 位于 UINavigationConroller 内

应用重新安装后的 iOS 位置权限

ios - 如何使用CALayer模糊图像

iphone - 如何在 Spotify iOS 应用程序中模仿可调整大小的 StatusBar