首页 > 解决方案 > 将原型单元连接到视图控制器 [Swift 4]

问题描述

我是编程新手,目前正在开发类似应用程序的新闻源。我有一个正常的表格视图,并且运行良好,但现在想尝试使用服装单元格类型。所以我创建了一个,并认为以通常的方式连接标签会非常好,但我错了。所以我想知道如何让我的文本标签连接到我的视图控制器,这样我就可以使用我的自定义单元格。

class ViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var newsfeedTableView: UITableView!

var ref: DatabaseReference!

var posts = [String]()


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (posts.count)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")

//here is where I need the custom label to get the posts 
    cell.textLabel?.text = posts[indexPath.row]
    cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 18.0)

    return cell
 }
}

服装细胞

标签: swiftuitableview

解决方案


创建该类的子类UITableViewCell并将 IBOutlets 连接到该类

class YourCell: UITableViewCell {
    @IBOutlet weak var customLabel: UILabel!
    ...
}

不要忘记在情节提要中设置原型单元的类:

在此处输入图像描述

然后在cellForRowAt数据源方法中将您的出列单元格向下转换为YourCell

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! YourCell

那么你就可以使用YourCell网点了

cell.customLabel.text = "SomeText"
...

推荐阅读