【发布时间】:2017-12-10 03:20:14
【问题描述】:
在为 iOS 开发应用程序时,我创建了一个结构,还创建了一个填充有该结构对象的数组。结构flavors 和descrip 有两个属性。我想从数组中的每个项目中获取每个 flavor 属性,并使用它来填充表格视图单元格的标签。数组中有六个项目,所以我想要六个标签以便它对应。所以标签 1 应该是巧克力片,标签 2 蜂蜜,标签 3 糖,依此类推。高度赞赏所有建议和提示。
Import UIKit
class FlavorController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var flavorTable: UITableView!
struct cookieInfo {
var flavor: String
var descrip: String
}
var cookies = [cookieInfo(flavor: "Chocolate Chip", descrip: "Filled with gooey, milk chocholate! A classic!"), cookieInfo(flavor: "Honey", descrip: "Baked and drizzled with 100% pure honey, a must-have for sweet lovers!"), cookieInfo(flavor: "Sugar", descrip: "Simplicity meets savory, a sugar cookie topped with sweet icing!"), cookieInfo(flavor: "Peanut Butter", descrip: "A cookie infused with creamy peanut butter, the perfect cookie treat!"), cookieInfo(flavor: "Snickerdoodle", descrip: "Sugar cookie coated in cinnamon & sugar, baked to perfection!"),cookieInfo(flavor: "Shortbread", descrip: "An underrated yet flavorful cookie just like your grandma used to make!")]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return cookies.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FlavorCellTableViewCell
//this is where I want to the text of each flavorLabel to be the flavor property of the struct
cell.flavorLabel.text = ??
return cell
}
【问题讨论】:
-
请注意,Swift 约定以大写字母开头的结构命名。顺便说一句,信息是多余的,我将其命名为
Cookie,并将descrip属性名称更改为info或detail。 -
顺便说一句,不要忘记在 viewDidLoad 或您的 IB 中将视图控制器设置为 tableview 委托和数据源。
标签: ios arrays swift struct label