约束未随设备方向更改而更新

我在tableView单元格中有一个颜色滑块 ,它从标签延伸到单元格的trailingAnchor。 我遇到的问题是当设备方向改变时,颜色滑块不会更新其约束,也不再延长单元格的整个长度。 下面是我在颜色滑块上设置约束的代码。 以下是显示我遇到的问题的图片。 如果我在呈现此场景时手机已处于横向,则颜色滑块可根据需要延伸单元格的整个长度。 但是,如果我在查看此场景时切换到横向,则滑块如下所示。 如果有帮助,这是完整的代码 。

滑块肖像 滑块景观

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添加代码,以便在ColorSlider的大小/位置发生更改时更新图层。 幸运的是, UIView上有一个专门针对此的方法。

 override func layoutSubviews() { super.layoutSubviews() gradientLayer.frame = bounds }