2016-10-26 3 views
1

이 내 데이터베이스 구조스위프트는 어떻게 내 데이터베이스에 값이있는 경우에만있는 tableview 셀을 표시 할

"type" : { 
     "A" : { 
     "nightAmount" : 5, 
     "noonAmount" : 2 
     }, 
     "B" : { 
     "nightAmount" : 5, 
     "noonAmount" : 3 
     }, 
     "C" : { 
     "nightAmount" : 2, 
     "noonAmount" : 5 
     }} 

내 tableviewCell 같은 레이블을 표시 할 수 있습니다 : -

1 차 전지 : A - noonAmount을 - 2

2 차 전지 : A - nightAmount - 5

3 셀 : B - noonAmount - 3

4 셀 : B - nightAmount - 5

5 세포 : C - noonAmount - 5

6 셀 : C - nightAmount - 2

그러나 양이 0이 될 수 있으며, 내가 원하지 않는 금액이 내 tableview 셀에 표시하려면 0입니다.

cellforrowat 함수는 무엇이라고합니까?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "confCell")! as UITableViewCell { 

그리고 여기입니다 내 numberofrowsinsection

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    if AnoontAmount >= 1 { 
     let V1 = 1 
    } else { V1 = 0 } 

    if ANightAmount >= 1 { 
     let V2 = 1 
    } else { V2 = 0 } 

    if BnoonAmount >= 1 { 
     let V3 = 1 
    } else { V3 = 0 } 

    if BNightAmount >= 1 { 
     let V4 = 1 
    } else { V4 = 0 } 

    if CnoonAmount >= 1 { 
     let V5 = 1 
    } else { V5 = 0 } 

    if CNightAmount >= 1 { 
     let V6 = 1 
    } else { V6 = 0 } 


    let cellTotal = V1 + V2 + V3 + V4 + V5 + V6 
    return cellTotal 

사람이이 작업을 수행하려면 적절한 방법이 있는지 말해 줄 수 거 일이 있는지 모르겠어요?

감사합니다. 하나의 VAmount = 0이 있는지

UPDATE는

나는 그렇게 배열의 인덱스를 제거 그냥 잘 작동, 이제 다음

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    var cellTotal = 0 

    if V1amount > 0 { 
     cellTotal += 1 
    } 

    if V2amount > 0 { 
     cellTotal += 1 
    } 

    if V3amount > 0 { 
     cellTotal += 1 
    } 


    if V4amount > 0 { 
     cellTotal += 1 
    } 


    if V5amount > 0 { 
     cellTotal += 1 
    } 

    if V6amount > 0 { 
     cellTotal += 1 
    } 

    return cellTotal 

} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 


    var mealtype : Array = ["TypeA", "TypeA", "TypeB", "TypeB", "TypeC", "TypeC"] 
    var mealtime : Array = ["lunch", "dinner", "lunch","dinner","lunch","dinner"] 
    var mealamount : Array = ["\(V1amount!)","\(V2amount!)","\(V3amount!)","\(V4amount!)","\(V5amount!)","\(V6amount!)"] 

    if V1amount == 0 { 
     mealtype.remove(at: 0) 
     mealtime.remove(at: 0) 
     mealamount.remove(at: 0) 
    } 

    if V2amount == 0 { 
     mealtype.remove(at: 1) 
     mealtime.remove(at: 1) 
     mealamount.remove(at: 1) 
    } 


    print (mealtype) 
    print (mealtime) 
    print (mealamount) 




    if let cell = tableView.dequeueReusableCell(withIdentifier: "confCell") as! confCell! { 

     cell.confMealName.text = mealtype[(indexPath as NSIndexPath).row] 
     cell.confNN.text = mealtime[(indexPath as NSIndexPath).row] 
     cell.confAmount.text! = mealamount[(indexPath as NSIndexPath).row] 

     return cell 
    } else { 
     return confCell() 
    } 

} 

문제로 내 코드를 업데이트 그것은 테이블 뷰 셀을 표시하지 않을 것입니다 하지만 VAmount = 0이 두 개 이상인 경우

그냥 이상하게 작동합니다. 프로그램이 실행되기 때문에 그럴 것 같습니다. f 롬 봇에 위로 ...이 아니라 한 번에 ...

방법이 코드를

이 할 수있는 더 나은 방법이있다 내가 확신을 개선하기 위해 말해 줄 수 사람이 있는가! :/

+0

실제로 원하십니까? 셀에 값 0 표시 안 함 –

+0

각 셀의 내용을 나타내는 데이터 개체 (예 : 이름, 시간, 양)를 만들 것을 제안합니다. json을 수신하면이를 데이터 오브젝트 목록에 따라 구문 분석하십시오. 금액이 비어 있으면 목록에 추가하지 마십시오. 이렇게하면 데이터 객체와 tableview의 list 셀, 즉 numberOfRowsInSection에 대한 1-1 매핑이 생기며 간단히 list.count를 반환 할 수 있습니다. cellForRowAtIndexPath의 경우 [indexPath.row] 목록으로 데이터 객체를 잡고 값에 따라 셀을 렌더링 할 수 있습니다. –

+0

@Jecky, 예. 예를 들어/A/noonAmount = 0 인 경우 5 행만 갖습니다. 그 모든 6 행을 가지고 쉽게, 난 그냥 0> 0 값을 가진 사람들을 보여줄 방법이 없어. – Ian

답변

2

내 댓글에 제안한 것처럼를, 하나의 방법은 각 셀의 내용을 보유하는 데이터 객체를 생성하는 것입니다. 이렇게하면 데이터 개체와 테이블 뷰의 목록 셀간에 1-1 매핑이 생깁니다.

먼저, 0이 아닌 양의 식사가있는 객체를 보관할 배열을 만듭니다. 이 작업은 데이터베이스에서 JSON을 가져 오는 위치 (예 : cellForRowAtIndexPath이 아님)에서 수행해야합니다. 이 예제에서는 데이터 객체에 대해 Swift 튜플을 사용하여 단순화 하겠지만 항상 오래된 Swift 객체를 사용할 수 있습니다. 각 식사 객체의 경우

// An array of Meal tuples, each of which can hold a type, time and amount) 
var meals:[(type: String, time: String, amount: Double)] = [] 

, 양이 비어있는 경우, 우리는 단순히 배열에 추가하지 않습니다 당신이 당신의 식사 배열과 사이에 1-1 매핑을 가지고 있기 때문에

if v1amount > 0 { 
    meals.append((type: "TypeA", time: "lunch", amount: v1amount)) 
} 
if v2amount > 0 { 
    meals.append((type: "TypeA", time: "dinner", amount: v2amount)) 
} 
if v3amount > 0 { 
    meals.append((type: "TypeB", time: "lunch", amount: v3amount)) 
} 
if v4amount > 0 { 
    meals.append((type: "TypeB", time: "dinner", amount: v4amount)) 
} 
if v5amount > 0 { 
    meals.append((type: "TypeC", time: "lunch", amount: v5amount)) 
} 
if v6amount > 0 { 
    meals.append((type: "TypeC", time: "dinner", amount: v6amount)) 
} 

의 tableview는 numberOfRowsInSection 위임 방법은 간단하게 구현 :

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // return the number of meals in your array 
    return meals.count 
} 

마찬가지로, cellForRowAtIndexPath을 위해, 당신은 단순히 관련 인덱스 배열에서 개체를 얻을 수하는 그 내용을 렌더링합니다 :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "confCell") as! confCell 
    // Get the meal object for this row 
    let meal = meals[indexPath.row] 

    // Populate the fields based on the meal's property 
    cell.confMealName.text = meal.type 
    cell.confNN.text = meal.time 
    cell.confAmount.text! = meal.amount 

    return cell 
} 
+0

안녕하세요 kenton, 당신의 논리는 완벽합니다 !! 당신의 코드는 내가 어떻게하고 싶은지처럼 보입니다. 하지만 Xcode는 "AnyObject에는 'time'타입의 값이 없습니다."오류가 계속 발생합니다. 가능성이 무엇이 잘못되었는지 모르겠다. – Ian

+0

어떤 라인? 식사 배열을 선언 할 때 위의 내 대답에 따라 배열이 보유하고있는 객체의 유형도 선언했는지 확인하십시오. –

+1

안녕하세요 kenton, 이제 완전히 작동합니다. 고맙습니다. 코드에서 많은 것을 배웁니다! – Ian

1

닫힌 범위에서 V1, V2 등이 선언 되었기 때문에 컴파일 오류가 발생하는 것을 제외하면 논리가 정상인 것처럼 보입니다.

나는이 같은 제안 :

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    var cellTotal = 6 

    guard AnoonAmount > 0 else {cellTotal -= 1} 

    guard ANightAmount > 0 else {cellTotal -= 1} 

    guard BnoonAmount > 0 else {cellTotal -= 1} 

    guard BNightAmount > 0 else {cellTotal -= 1} 

    guard CnoonAmount > 0 else {cellTotal -= 1} 

    guard CnightAmount > 0 else {cellTotal -= 1} 

    return cellTotal  
} 
+1

안녕하세요 엘레나, 답장을 보내 주셔서 감사합니다! 당신의 코드가 완벽한 의미로 보이는 것처럼, 나는 그것을 시도 할 것이다! anyidea 어떻게 Indexpath 함수를 cellforrowat합니까? 감사합니다 – Ian

+0

이안, 당신은 충분히 가지고 [게시물] (http://stackoverflow.com/questions/24022763/uitableview-in-swift). – Elena

관련 문제