【问题标题】:UITableView background view auto resizingUITableView 背景视图自动调整大小
【发布时间】:2021-01-21 11:53:23
【问题描述】:

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

当您将视图分配给此属性时,表格视图会自动 调整该视图的大小以匹配它自己的边界。

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

【问题讨论】:

  • 您可以根据需要将约束添加到您的红色小方块视图到通用 UIView。并将该通用视图添加到 tableView 的 backgroundView。您还可以将该通用视图的背景颜色设置为 UIColor.clear。这样就不会影响TableView的实际背景颜色

标签: ios swift autolayout


【解决方案1】:

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

你可以直接把这个 bgView 添加到 tableView 中,然后把这个新的 subview 发送回去。
这样您也可以保留表格视图的背景颜色。

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

【讨论】:

  • 为什么我在提问之前没有测试约束:))谢谢
  • 在阅读了我了解到的其他 cmets 后,当数据未正确加载时,您正在添加一个重新加载按钮。在这种情况下,您不应该改为 sendSubviewToBack,您应该考虑使用bringToFront。明智地使用这些方法!我希望你达到了你的预期。
  • 是的,我删除了 sendSubviewToBack,现在一切正常
【解决方案2】:

您可以在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 也应该有清晰的背景。

【讨论】:

  • 实际上我想在tableView中放置一个重新加载按钮,当数据在tableView中没有正确加载时,所以我认为它不应该在tableView下,所以它不能再点击了,但是感谢你的好方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-17
  • 2013-06-08
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多