我需要支持 iOS 8.1 和 8.2,但我不记得如何正确设置 layoutMargins,已经搜索了很多(在我自己的旧项目、Google、SO、OpenRadar 中)。
从 iOS 8.3 开始一切正常。
谁能给我指出正确的方向?
对于自定义 Cell 及其 contentView,我在 IB 中设置了“Preserve Superview Margins”。 “跟随可读宽度”(iOS9) 关闭。
在 iPad Air 2 模拟器上测试。
iOS 8.1 和 8.2(UILabel 的左边距太小):
iOS 8.3 到 9.3(正确):
像往常一样自动布局到 contentView(刚刚添加顶部/底部 +3px):
试图通过代码检查 layoutMargins(在这个 Cell 类中),但它们是正确的。
这是完整的单元格类:
class TextLabelTableViewCell: UITableViewCell {
@IBOutlet weak var customTextLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configure(text: String?) {
customTextLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
customTextLabel.text = text
customTextLabel.accessibilityLabel = text
}
override func layoutSubviews() {
super.layoutSubviews()
debugPrint("layoutMargins: ", layoutMargins)
debugPrint("contentView.layoutMargins: ", contentView.layoutMargins)
debugPrint("separatorInsets: ", separatorInset)
/*
"layoutMargins: " __C.UIEdgeInsets(top: 8.0, left: 16.0, bottom: 8.0, right: 16.0) - 8, 16, 8, 16
"contentView.layoutMargins: " __C.UIEdgeInsets(top: 8.0, left: 16.0, bottom: 8.0, right: 16.0) - 8, 16, 8, 16
"separatorInsets: " __C.UIEdgeInsets(top: 0.0, left: 16.0, bottom: 0.0, right: 0.0) - 0, 16, 0, 0
*/
}
}
检查 Reveal 中的单元格。一切都是正确的,除了 UILabel。这是上面单元格中标签的屏幕截图。帧 X 应为 16。
找到这个线程:UITableViewCell with autolayout left margin different on iPhone and iPad
有趣的是对第一个和已接受的答案的评论:
So I tried it on the 8.1 simulator and indeed, the margins are too narrow, meaning that the superview's layout margins are not preserved... However this is a bug that Apple has fixed in 8.3 and somehow fixed again in iOS 9. – Jonas Zaugg
好吧,这是一个错误是显而易见的。但是你通常如何解决?那就是我忘了。为 8.0 到 8.2(UIAppearance ftw)手动设置 layoutMargin 和 separatorInsets 的每个插图?
Sankalap Yaduraj Singh 建议的解决方案,即为 leadingMargin 设置一个额外的 margin 常量,不有效:
我发现:如果我通过 UIAppearance 将 layoutMargin 设置为大于设备默认值(通常 iPad 上为 16,iPhone 上为 8),则会正确应用较大的边距:
// Experimental: TableViewCells Margin Bugfix for iOS 8.0 to 8.2
UITableViewCell.appearance().layoutMargins = UIEdgeInsetsMake(8, 17, 8, 16)
注意 17,而不是 iPad 上此测试的 16。
如前所述,这是一个已知的 iOS 8.1/8.2 错误。我已经知道了,问题是如何以干净的方式解决问题。
有趣的事实:如果我在 Reveal 中将 UILabel 的前导约束常量从 0 调整为 1,然后再调整回 0,则位置是正确的。看起来这个 8.1/8.2 错误是一个 AutoLayout 错误。
最佳答案
关于ios - UILabel 自动布局忽略 iOS 8.1 和 8.2 上的 UITableViewCell 的左边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36550417/