2017-02-16 105 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 
    } 
} 

谢谢大家对我的帮助