簡體   English   中英

Swift - 在 tableView.selectRow 中更改背景顏色

[英]Swift - Change background color in tableView.selectRow

我有一個具有所有正確行為的 tableView,但我試圖將選定行的背景顏色從默認的灰色更改為綠色,並且 tableView 表現得很奇怪。

默認顏色的當前行為:頁面加載並且第一個表格部分的第一行被選擇為默認值(灰色背景)。 如果用戶單擊另一行,則取消選擇第一行,單擊的將獲得灰色背景。 這段代碼:

private var scrolledToItitialSelection = false
didSet {
    tableView.reloadData()
    if let selected = self.model.selectedRow { // selectedRow returns an indexPath
        tableView.selectRow(at: selected, animated: true, scrollPosition: scrolledToInitialSelection ? .none : .middle

        scrolledToItitialSelection = true
    }
}

我試圖實現完全相同的行為,只是使用不同的背景顏色。 但是在下面的代碼中,tableView 加載並按預期選擇了第一個表格部分的第一行,但第二部分的第二行也是如此。 另外,如果我單擊默認選擇的行下方的行,現在我有 4 個選定的行:第一部分中有兩個,第二部分中有兩個。

private var scrolledToItitialSelection = false
didSet {
    tableView.reloadData()
    if let selected = self.model.selectedRow { // selectedRow returns an indexPath
        tableView.selectRow(at: selected, animated: true, scrollPosition: scrolledToInitialSelection ? .none : .middle
        let selectedCell:UITableViewCell = tableView.cellForRow(at: selected)!
        selectedCell.contentView.backgroundColor = .green
        selectedCell.accessoryView.backgroundColor = .green
        scrolledToItitialSelection = true
    }
}

UITableViewCell選擇顏色是單元格子視圖的背景顏色。

你可以試試這個:

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

/// dequeueReusableCellWithIdentifier...
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.green
cell.selectedBackgroundView = backgroundColorView
}

暫無
暫無

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

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