iOS TableView无数据时背景视图无法居中问题求助
嗨,这个问题我之前也碰到过!咱们来一步步拆解为啥会这样,以及怎么解决~
问题根源
首先,你直接设置 emptyListView.center = tableView.center 是没用的——因为当你把视图设为tableView的backgroundView后,UITableView会接管它的布局,手动设置的center或者frame很容易被系统布局覆盖。另外还有个关键细节:你的EmptyListView从Xib加载后,内部的图片和标签可能没有设置居中约束,如果内部控件是居顶排列的,哪怕EmptyListView本身大小正确,整体看起来还是会居顶显示。
解决方案
第一步:确保Xib内部约束正确
打开你的EmptyListView.xib,选中根视图,给内部的图片和标签设置相对于根视图的水平居中和垂直居中约束:
- 如果是图片+标签上下排列,可以把它们放进一个垂直栈视图,再给栈视图设置
centerX和centerY等于根视图的对应属性 - 如果是单独控件,直接给每个控件添加
centerX约束,以及垂直方向的居中/间距约束
这样不管根视图的大小怎么变,内部控件都会保持在中间位置。
第二步:正确设置BackgroundView的布局
有两种可靠的方式实现:
方式一:使用Autoresizing Mask(简单直接)
加载完视图后,设置它的frame匹配tableView的bounds,并开启自动拉伸,适配tableView的尺寸变化:
let emptyListView = EmptyListView.instanceFromNib() as! EmptyListView emptyListView.labelNothingFound.text = AppMessages.NoDataFound.noRestaurentFound // 让视图填充整个tableView的当前范围 emptyListView.frame = tableView.bounds // 开启宽高自动拉伸,适配屏幕旋转等场景 emptyListView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.backgroundView = emptyListView tableView.separatorStyle = .none
方式二:使用Auto Layout(现代布局方式)
如果你的项目更依赖Auto Layout,可以关闭自动转换约束,手动添加填充整个tableView的约束:
let emptyListView = EmptyListView.instanceFromNib() as! EmptyListView emptyListView.labelNothingFound.text = AppMessages.NoDataFound.noRestaurentFound tableView.backgroundView = emptyListView // 关闭系统自动生成的约束 emptyListView.translatesAutoresizingMaskIntoConstraints = false // 添加约束让视图完全填充tableView NSLayoutConstraint.activate([ emptyListView.topAnchor.constraint(equalTo: tableView.topAnchor), emptyListView.leadingAnchor.constraint(equalTo: tableView.leadingAnchor), emptyListView.trailingAnchor.constraint(equalTo: tableView.trailingAnchor), emptyListView.bottomAnchor.constraint(equalTo: tableView.bottomAnchor) ]) tableView.separatorStyle = .none
这样操作后,你的无数据提示视图就能完美居中在tableView里啦~
内容的提问来源于stack exchange,提问作者TechChain
相关产品推荐
相关产品推荐

