You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Xcode中的TableViewCell无法被选中或高亮?

嘿,我来帮你搞定这个需求!要让TableViewCell点击时完全不出现高亮或选中状态,有两种超简单的实现方式,看你习惯哪种操作:

方法一:通过Interface Builder(可视化操作)

这种方式不用写代码,点点鼠标就搞定:

  • 打开你的Storyboard或者XIB文件,找到对应的TableViewCell
  • 选中这个Cell,打开右侧的Attributes Inspector(就是那个带小齿轮的属性检查器面板)
  • 找到「Selection」选项,把默认的Default改成None就大功告成啦!
方法二:通过代码实现

如果更喜欢用代码控制,也有两种场景的写法:

场景1:在自定义Cell类中设置

如果你用了自定义的TableViewCell,可以在Cell的初始化方法里统一设置:

Swift 版本

class YourCustomCell: UITableViewCell {
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupCell()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupCell()
    }
    
    private func setupCell() {
        // 禁用选中高亮
        self.selectionStyle = .none
    }
}

Objective-C 版本

@interface YourCustomCell : UITableViewCell
@end

@implementation YourCustomCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupCell];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setupCell];
    }
    return self;
}

- (void)setupCell {
    // 禁用选中高亮
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}

@end

场景2:在TableView的代理方法中设置

如果是系统默认Cell或者不想修改Cell类,可以在创建Cell的时候直接设置:

Swift 版本

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier", for: indexPath)
    // 这里添加Cell的其他配置逻辑
    cell.selectionStyle = .none
    return cell
}

Objective-C 版本

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YourCellIdentifier" forIndexPath:indexPath];
    // 这里添加Cell的其他配置逻辑
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

两种方法最终效果完全一致,选你顺手的来就行~如果还有其他细节需要调整,随时告诉我!

内容的提问来源于stack exchange,提问作者Swope

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:23:19