UITableView 背景视图自动调整大小

UITableView background view auto resizing

我想在我的 tableView (tableView.backgroundView) 中心有一个不填满 tableView 的小红色方块。但根据苹果

When you assign a view to this property, the table view automatically resizes that view to match its own bounds.

所以没有办法阻止这种调整大小和填充 tableViewBackgroundView?

您可以在 tableView 下面添加一个子视图,而不是使用 backgroundView 属性,如下所示:

//for example inside viewDidLoad()

let bgView = UIView()
bgView.translatesAutoresizingMaskIntoConstraints = false

self.view.insertSubview(bgView, belowSubview: tableView)
NSLayoutConstraint.activate([
    bgView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
    bgView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
    bgView.widthAnchor.constraint(equalToConstant: 50),
    bgView.heightAnchor.constraint(equalToConstant: 50)
])

bgView.backgroundColor = .red

但要查看 bgView,您必须设置 tableView.backgroundColor = .clear。另外你的UITableViewCells也应该有一个清晰的背景。

@ 解决方案完全没问题。但是,如果您正在寻找不同的东西。给你

您可以将这个 bgView 直接添加到 tableView 并将这个新的子视图发送到后面。
这样您也可以保留 table 视图的背景颜色。

// after your setup
let bgView = UIView()
tableView.addSubview(bgView)
// add constraints after disabling autoresizing mask
bgView.backgroundColor = UIColor.red
tableView.sendSubview(toBack: bgView)