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

如何将UITableView原型Cell中的背景气泡UIView移至底层?

问题解决:将UITableViewCell的背景气泡移至内容后方

问题原因

你直接把backgroundBubble添加到了Cell本身上(addSubview(backgroundBubble)),但Storyboard中添加的标签、图像等控件,默认都是放在Cell的contentView子视图里的。当调用sendSubviewToBack(backgroundBubble)时,气泡会被放到Cell的所有子视图最底层——也就是contentView的下方,自然就被contentView完全遮挡住了。

解决方案

方案1:将气泡添加到contentView并移至底层

把气泡的父视图改为contentView,再将它发送到contentView子视图的最底层,这样就能让它处于标签、图像的后方:

let backgroundBubble = UIView()

override func awakeFromNib() {
    super.awakeFromNib()
    backgroundBubble.backgroundColor = .yellow
    backgroundBubble.translatesAutoresizingMaskIntoConstraints = false
    // 改为添加到contentView中
    contentView.addSubview(backgroundBubble)
    let constraints = [
        backgroundBubble.topAnchor.constraint(equalTo: Label.topAnchor, constant: 0),
        backgroundBubble.leadingAnchor.constraint(equalTo: Label.leadingAnchor, constant: 0),
        backgroundBubble.bottomAnchor.constraint(equalTo: Label.bottomAnchor, constant: 0),
        backgroundBubble.trailingAnchor.constraint(equalTo: Label.trailingAnchor, constant: 0)
    ]
    NSLayoutConstraint.activate(constraints)
    // 将气泡移至contentView的子视图底层
    contentView.sendSubviewToBack(backgroundBubble)
}

方案2:直接插入到contentView子视图的最前方(索引0)

也可以通过插入子视图的方式,直接把气泡放在contentView子视图列表的最开头,默认就会处于其他控件的后方:

let backgroundBubble = UIView()

override func awakeFromNib() {
    super.awakeFromNib()
    backgroundBubble.backgroundColor = .yellow
    backgroundBubble.translatesAutoresizingMaskIntoConstraints = false
    // 插入到contentView子视图的索引0位置
    contentView.insertSubview(backgroundBubble, at: 0)
    let constraints = [
        backgroundBubble.topAnchor.constraint(equalTo: Label.topAnchor, constant: 0),
        backgroundBubble.leadingAnchor.constraint(equalTo: Label.leadingAnchor, constant: 0),
        backgroundBubble.bottomAnchor.constraint(equalTo: Label.bottomAnchor, constant: 0),
        backgroundBubble.trailingAnchor.constraint(equalTo: Label.trailingAnchor, constant: 0)
    ]
    NSLayoutConstraint.activate(constraints)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:43:25