swift问题数组无法打印到collectionviewcell标签
Posted
技术标签:
【中文标题】swift问题数组无法打印到collectionviewcell标签【英文标题】:Swift problem the array can't print to the collectionviewcell label 【发布时间】:2020-11-10 13:39:38 【问题描述】:我尝试将集合视图作为这个 url How to make a simple collection view with Swift
但是标签无法连接到collectionviewcell.swift:
有一个Mycollectionview.swift:
只能显示背景,不能打印文字:
MyControllectionCell.swift
import UIKit
class MyCollectionViewCell: UICollectionViewCell
@IBOutlet weak var myLabel: UILabel!
ViewController.swift
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate
let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
return self.items.count
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel?.text = self.items[indexPath.item] // The row value is the same as the index of the desired text within the array.
cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
return cell
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
// handle tap events
print("You selected cell #\(indexPath.item)!")
【问题讨论】:
【参考方案1】:tldr;先看看教程。
长答案:
我猜你正在尝试将UILabel
连接到你的UIViewController
子类而不是UICollectionViewCell
。
但我有点不确定,因为您提供的代码 sn-p 不完整...
例如。我没有看到您的 UICollectionView
属性列在您的 UIViewController
子类下。
所以这只是我的假设。
也不确定您的 UICollecitonView 的 delegate
和 dataSource
属性是否正确设置。
仔细检查label
不是cellForItemAt
方法中的nil
,并且它是具有非零框架的单元格视图层次结构的一部分。
但老实说,您绝对应该先查看教程。有很多很棒的教程可以帮助您逐步实现这一点。
【讨论】:
以上是关于swift问题数组无法打印到collectionviewcell标签的主要内容,如果未能解决你的问题,请参考以下文章