2017-12-10 1 views
0

iOS 용 앱을 개발하면서 구조체를 만들었으며 구조체의 객체로 채워진 배열을 만들었습니다. 구조체 flavorsdescrip의 두 가지 속성이 있습니다. 배열의 각 항목에서 각 flavor 속성을 가져 와서 테이블보기 셀의 레이블을 채우는 데 사용하고 싶습니다. 배열에 여섯 개의 항목이 있으므로 여섯 개의 레이블이 필요합니다. 따라서 레이블 하나는 초콜릿 칩, 레이블 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

참고. Btw Info is redundant 나는'Cookie'라고 이름을 짓고'descrip' 속성 이름을'info' 또는'detail'로 변경합니다. –

+0

Btw 뷰 컨트롤러를 viewDidLoad 또는 IB에서 tableview 대리자 및 dataSource로 설정하는 것을 잊지 마십시오. –

답변

1

이것은 간단한 필드 액세스와 간단한 필드 액세스입니다.

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

또는, 더 간단하게 : 그것은 대문자로 시작하여 구조에 이름을 스위프트 규칙이라고

cell.flavorLabel.text = cookies[indexPath.row].flavor 
관련 문제