2015-10-20 1033 views
1

也許我的問題很簡單,我太傻了。 我的問題是,我要訪問外部獲取任何tableView函數之外的indexpath

overide func tableView(...) 

所以我在我的TableView類的indexPath,並有一個單獨的類,如:

func setColor() 
{ 
... 
} 

這個類裏面我要訪問的indexPath 。我怎樣才能做到這一點?

+0

傳遞indexPath作爲參數。 – rmaddy

+0

你需要澄清你的目標是什麼。如何以及何時調用這個'setColor'方法?它是什麼課程? – rmaddy

+0

我在類TableView中,從另一個類的外部調用此函數,名爲setColor。 – Anokrize

回答

1

indexPath是一個對象,它被創建並傳遞給UITabelViewDelegate或UITableViewDataSource方法。它可以讓你指出哪個單元格被加載/點擊等。

所以你將無法從外部訪問這個對象。如果你想改變一些細胞的某些物質,例如您應該將顏色存儲在屬性中的backgroundColor,更改此屬性並強制重繪。在創建單元格的委託方法中,使用此屬性來設置顏色。

這是一些示例代碼。

的ViewController

class TestTableViewController: UIViewController, UITableViewDelegate { 

    // Store array of color 
    var backColors = [UIColor.redColor(), UIColor.greenColor()] 


    // Method which changes color 
    func setColor(row: Int, color: UIColor) { 
     backColors[row] = color 
    } 

    // Override draw 
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     // Create your cell 
     // ... 

     // Set color 
     cell.backgroundColor = backColors[indexPath.row] 
    } 
} 
+0

是的我想改變單元格的背景顏色。所以我應該強制重新加載tableView,然後在cellforRowAtIndexPath裏面,我應該設置顏色? – Anokrize

+0

這是我如何做到這一點。將顏色存儲在控制器中,強制重繪,cellforRowAtIndexPath方法使用此顏色。 – SnowMax

相關問題