2017-12-10 5 views
0

iOS向けのアプリケーションを開発するにあたり、私は構造体を作成しました。構造体のオブジェクトでいっぱいの配列も作成しました。構造体flavorsdescripの2つのプロパティがあります。配列の各項目からそれぞれflavorプロパティを取得し、それを使用して表ビューのセルのラベルを埋めたいとします。配列に6つの項目があるので、6つのラベルが対応するようにします。ラベル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 

} 
+0

注:

let cookie = cookies[indexPath.row] let flavor = cookie.flavor cell.flavorLabel.text = flavor 

それとも、もっと簡単に。 Btw Info is redundant私はそれを 'Cookie'と名付け、' descrip'プロパティ名を 'info'または' detail'に変更します。 –

+0

BtwビューコントローラをviewDidLoadまたはIBのtableviewデリゲートとdataSourceとして設定することを忘れないでください。 –

答えて

1

これは単純なアレイアクセスとこれに続く単純なフィールドアクセスです。大文字で始まるあなたの構造体に名前を付けるスウィフト慣例であることを

cell.flavorLabel.text = cookies[indexPath.row].flavor 
関連する問題