2017-02-16 107 views
1

我的VC中有一個UITableView,基本上我想要的是它的第一部分是不可打的。但是我不能使用isUserInteractionEnabled ,因爲我在本節的每一行中都有UISwitch。設置selectionStyle.none沒有任何變化。我只能在界面檢查器中選擇No Selection以禁用這些行,但會禁用整個表。我該怎麼辦?UITableViewCell在點擊時突出顯示

編輯

這裏是我的自定義單元格類

class CustomCell: UITableViewCell { override func setHighlighted(_ highlighted: Bool, animated: Bool) { if if highlighted { self.backgroundColor = ColorConstants.onTapColor } else { self.backgroundColor = .clear } } override func setSelected(_ selected: Bool, animated: Bool) { if selected { self.backgroundColor = ColorConstants.onTapColor } else { self.backgroundColor = .clear } } }

+1

檢查:http://stackoverflow.com/questions/2267993/uitableview-how-to-disable-selection-for-some-rows-but-not-others – Priyal

回答

3

您可以在第一部分中的所有UITableViewCellsselectionStyle設置爲.none如下:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "YOURIDENTIFIER") 

    if indexPath.section == 0 { 
     cell.selectionStyle = .none 
    } else { 
     cell.selectionStyle = .default 
    } 

    return cell 
} 

然後在你的didSelectRowAtIndexPath()方法可以檢查if (indexPath.section != YOURSECTION)

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    if indexPath.section == 0 { 
     // DO NITHING 
    } else { 
     // DO WHATEVER YOU WANT TO DO WITH THE CELLS IN YOUR OTHER SECTIONS 
    } 
} 
+0

正如我所說,它仍然在水龍頭上突出顯示。 Mb的原因是,將selectionStyle設置爲none可以避免執行didSelectRowAt,但它仍然會調用willSelectRowAt –

+0

我發現原因並且這非常愚蠢。我忘了,我在我的自定義UITableViewCell子類中重寫了setHighlighted函數。我想改變輕拍細胞的顏色。我應該怎麼做,而不是我做了什麼?答案已更新 –

0

您必須設置每個單元中的選擇樣式代碼。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = table.dequeue... 

    if indexPath.section == 0 { 
     cell.selectionStyle = .none 
    } else { 
     cell.selectionStyle = .default 
    } 

    return cell 
} 
0

在cellForRowAt添加cell.selectionStyle = .none

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    if(indexPath.section == desiredSection){ 
     cell.selectionStyle = .none 
     return cell; 
    } 
0

所以,我發現爲什麼與selectionStyle設置爲.none細胞得到了自來水突出的原因。因爲我重寫setHighlighted方法UITableViewCell(如問題所示)我加shouldHighlightRowAt方法是這樣的:

func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { 
    if indexPath.section == 0 { 
     return false 
    } else { 
     return true 
    } 
} 

謝謝大家對我的幫助