我有一个 color slider在从标签延伸到单元格的 trailingAnchor 的 tableView 单元格中。我遇到的问题是当设备方向发生变化时,颜色 slider 不会更新其约束并且不再延伸单元格的全长。下面是我在颜色 slider 上设置约束的代码。以下是显示我遇到的问题的图片。如果我呈现此场景时我的手机已经处于横向,则颜色 slider 会根据需要扩展单元格的整个长度。但是,如果我在查看此场景时切换到横向,则 slider 将如下所示。这是 full code如果有帮助的话。
func configureColorSlider() {
let colorSlider = ColorSlider()
let xCell = colorCell.contentView.bounds.width
let yCell = colorCell.contentView.bounds.height
colorSlider.frame = CGRect(x: xCell / 4, y: yCell / 4, width: 200, height: 24)
colorSlider.orientation = .horizontal
colorSlider.addTarget(self, action: #selector(ConfigureTimestampTableViewController.changedColor(_:)), for: .valueChanged)
colorCell.contentView.addSubview(colorSlider)
colorSlider.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([colorSlider.leadingAnchor.constraint(equalTo: colorLabel.trailingAnchor, constant: 8),
colorSlider.trailingAnchor.constraint(equalTo: colorCell.contentView.trailingAnchor, constant: -8),
colorSlider.topAnchor.constraint(equalTo: colorCell.contentView.topAnchor, constant: 8),
colorSlider.bottomAnchor.constraint(equalTo: colorCell.contentView.bottomAnchor, constant: -8) ])
}
最佳答案
CALayers
不会根据其父级 UIView
的大小调整而调整大小,无论是通过自动布局还是手动调整。
您只需向 ColorSlider
添加代码,当 ColorSilider
的大小/位置发生变化时更新图层。幸运的是,UIView
上有一个专门用于此的方法。
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = bounds
}
关于ios - 约束不随设备方向变化而更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40681639/