簡體   English   中英

在 iOS Swift 中更改單個 UITableView 單元格的顏色

[英]Changing color of single UITableView Cell in iOS Swift

我希望能夠更改單個 UITableView 單元格的顏色。 在我的 tableView(editActionsForRowAtIndexPath) 中,我可以滑動單元格並選擇一個按鈕來更改背景顏色,但是當我將單元格滾動到屏幕外時,它會變回來。 我如何讓它保持顏色? 謝謝

假設您的 tableView 中只有一個部分有很多行,您需要在 tableView:cellForRowAtIndexPath: 方法中執行此操作:

if (indexPath.row == coloredCellIndex) {
     cell.backgroundColor = UIColor.RedColor()
} else {
     cell.backgroundColor = UIColor.WhiteColor()
}

您需要在此函數之外的任何地方設置變量 colouredCellIndex,例如在 viewDidLoad

抱歉,我只能用 Objective-C 寫我的答案。 但我希望你能明白我的意思。

如果您使用的是自定義原型單元格,那么您可以向自定義表格視圖單元格類添加一個屬性,並存儲該單元格所需的當前顏色,然后再重新加載該顏色。

示例代碼:

在 CustomTableViewCell.h

@interface CustomTableViewCell : UITableViewCell

@property (nonatomic) UIColor *cellColor;

- (void)reloadBackgroundColor

@end

在 CustomTableViewCell.m 中

- (void)reloadBackgroundColor
{
    self.backgroundColor = cellColor; //this is just a sample.
}

然后在每次重新加載單元格時,您都可以設置該顏色。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

CustomTableViewCell *tableCell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomTableCellIdentifier"];

[tableCell reloadBackgroundColor];

return tableCell;

現在,每次滾動表格時,都會加載要設置到該單元格的顏色。

如果您沒有使用自定義原型單元格,那么我建議您將每個單元格所需的顏色存儲在字典中,並以其索引為鍵。 然后,每次重新加載時,您只需將其再次分配給該單元格。

我希望這可以幫助你。 :)

斯威夫特 3

查看已加載

self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")

單元格換行

cell.backgroundColor = .black
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell:CustomTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "myCell") as! CustomTableViewCell

cell.accessoryType = .none
cell.backgroundColor = .black

return cell
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM