gpt4 book ai didi

xcode - 如何在 Swift 中从具有多种内容类型的字典制作表格?

转载 作者:可可西里 更新时间:2023-10-31 23:54:16 25 4
gpt4 key购买 nike

我用 NSDictionary 对象创建了一个 NSArray,其中包含从 api 下载的内容。我还在 main.storyboard 上创建了一个 tableview 对象,其中包含一个带有 UIImage 标签和两个文本标签的原型(prototype)单元格作为其内容。我如何将数据从数组放到表格中,以便每个与我的原型(prototype)具有相同样式的单元格显示数组中 NSDictionary 的内容。

最佳答案

你必须实现 UITableViewDataSource 方法
记得将 tableView 的 dataSource 属性设置为 ViewController
比起从数组中获取一个对象(您的 NSDictionary)并使用其数据设置单元格标签和 imageView。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell

这是 Swift 中的完整代码示例。 Objective-C 非常相似

class MasterViewController: UITableViewController {

var objects = [
["name" : "Item 1", "image": "image1.png"],
["name" : "Item 2", "image": "image2.png"],
["name" : "Item 3", "image": "image3.png"]]

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

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

let object = objects[indexPath.row]

cell.textLabel?.text = object["name"]!
cell.imageView?.image = UIImage(named: object["image"]!)
cell.otherLabel?.text = object["otherProperty"]!

return cell
}

}

关于xcode - 如何在 Swift 中从具有多种内容类型的字典制作表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26453675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com