2016-08-17 31 views
0

我試圖在我的表視圖中生成單元格,每個單元格在右側都有動態允許的按鈕;一些帶2個按鈕,一些帶4個按鈕。問題是,雖然表格視圖按我喜歡的方式加載,但是在滾動時,單元最終都會有4個按鈕 - 即使是那些只有2個按鈕的按鈕。如何在Swift中保留表單繼承關係

我在做什麼錯?

這裏是我的代碼:

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

let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell 

cell.textLabel?.text = self.items[indexPath.row][0] 
cell.accessibilityLabel = self.items[indexPath.row][bigSort] 

cell.selectionStyle = .None 

for x in 0..<4 
{ 
    let button = UIButton() 
    let marginStart = w - tickWidthInCell * 4 - 9 + (tickWidthInCell + 2) * x 
    let margin = CGFloat(marginStart) 

    button.frame = CGRectMake(margin, CGFloat(cellHeightMargin), CGFloat(tickWidthInCell), CGFloat(tickHeightInCell)) 

    button.layer.borderColor = GRAY.CGColor 

    if (self.items[indexPath.row][1] == "Special" && x % 2 != 0) 
    { 
     button.backgroundColor = UIColor.clearColor() 
     button.layer.borderColor = UIColor.clearColor().CGColor 
     //button.hidden = true 

    } 
    else 
    { 
     button.addTarget(self, action: #selector(cellButtonClicked), forControlEvents: .TouchUpInside) 
     button.backgroundColor = UIColor(netHex:0x222222) 
     button.layer.borderWidth = 1 
    } 
    cell.contentView.addSubview(button) 

} 


return cell 
} 
+1

我想你錯過了代碼的關鍵部分。給我們你的整個方法,你去哪裏出細胞。 –

+0

在單元格的滾動方法中使用某些東西,否則單元格將被重用並且它將會發生。 –

+1

滾動時記住單元格重新使用。你需要確保你的單元格可以重用你的單元類的'prepareForReuse',並從那裏的早期初始化中清除任何狀態... – Shripada

回答

0

這是因爲tableview中重用您定義的細胞。 要控制重複使用應該如何進行,請在您的自定義UITableViewCell中覆蓋prepareForReuse。並始終將它們重置爲您想要的狀態,例如將單元格設置爲只有2個按鈕)

或者在cellForRowAtIndexPath中,您可以處理兩種情況都有2個按鈕或4個。 (當您指定要求2按鈕確保你隱藏其他2)