iOS - subivew 不能在 UITableViewCell 中居中

标签 ios swift xcode uitableview autolayout

这真的很奇怪。 无论我如何设置约束,它都会在布局后忽略所有约束。 我尝试使用 cell.indicator.center = cell.centercell.indicator.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 但仍然没有用。 有什么特殊的方法可以让 UITableViewCell 中的 subview 居中吗?

加载单元格.xib

enter image description here

截图(模拟器)

enter image description here

更新:

在尝试了@Vibha Singh 的建议后,我将这些代码放入我的 LoadingCell 中。

override func layoutSubviews() {
    print("layoutSubviews")
    print(center)
    print(contentView.bounds)
    indicator.center = contentView.center
}

它打印了这些行:

layoutSubviews
(207.0, 1055.16668891907)
(0.0, 0.0, 414.0, 44.6666666666667)

但是指标还是没有居中。

更新:

我通过创建一个带有指示器的新单元格来修复它。 它们都具有完全相同的约束。新的按预期居中,但旧的仍然位于左上角。

更新:

我第一次确实使用了centerX和centerY作为约束。但它没有用。所以我必须尝试另一种方法。这就是我在第一个屏幕截图中使用这么多约束的原因。

这是两个完全相同的 xibs 的屏幕截图。

他们都使用相同的代码出队。

let dequeue = tableView.dequeueReusableCell(withIdentifier: SharedCell.loading.rawValue, for: indexPath)

if let cell = dequeue as? CenterLoadingCell {
    cell.indicator.startAnimating()
}
else if let cell = dequeue as? LoadingCell {
    cell.indicator.startAnimating()
}

return dequeue

第一个名为LoadingCell,不以模拟器为中心。

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

第二个名为CenterLoadingCell,是我在提出这个问题后创建的。而这个以模拟器为中心。

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

最佳答案

您通过添加不必要的约束来混淆您的布局设置。检查此实现。

Image with Constraint

使用自定义单元格: enter image description here

关于iOS - subivew 不能在 UITableViewCell 中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44652276/

相关文章:

ios - 用于应用程序 API 的 Parse.com Javascript SDK 还是普通的 iOS SDK?

ios - 如何传递一个额外的参数

ios - 如何在 Swift 中将文本添加到 .csv 数据中?

iphone - iOS 无法隐藏工具栏 UIbarButtonItem

objective-c - 如何在 iOS 和 Mac 中使用搜索字段控件?

ios - xCode 在运行应用程序时失去与设备的连接

ios - 使用字符串作为 [JSON valueForKeyPath] 选择器的一部分?

iOS swift 如何更改英语以外的基本语言

swift - 创建加载图像/事件指示器,直到图像快速显示在屏幕上

ios - 创建 ViewController 时,无法删除 "also create a xib"