【问题标题】:Constraints not updating with device orientation change约束不随设备方向更改而更新
【发布时间】:2016-11-18 16:16:11
【问题描述】:

我在 tableView 单元格中有一个color slider,它从标签延伸到单元格的 trailingAnchor。我遇到的问题是当设备方向更改时颜色滑块不会更新其约束并且不再延伸单元格的全长。下面是我在颜色滑块上设置约束的代码。下面是显示我遇到的问题的图像。如果在呈现此场景时我的手机已经处于横向,则颜色滑块会根据需要扩展单元格的整个长度。但是,如果我在查看此场景时切换到横向,滑块将如下所示。如果有帮助,这里是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) ])


  }

【问题讨论】:

  • ColorSlider的内容是用CALayers吗?他们不会使用自动布局更新其大小/位置。
  • 确实如此。使用 CAGradientLayer() 绘制颜色滑块。那一定是问题所在。如果我不能使用自动布局,您是否有调整滑块大小的建议?

标签: ios swift autolayout


【解决方案1】:

CALayers 的大小不会响应其父 UIView 的大小调整,无论是通过自动布局还是手动调整。

您只需向您的ColorSlider 添加代码,当ColorSilider 的大小/位置发生变化时更新图层。幸运的是,UIView 上有一个专门用于此的方法。

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

【讨论】:

  • 谢谢!当我添加它时,Xcode 让我将它添加到这个函数中,但它确实有效!没有 public 它给了我消息“重写实例方法必须与其封闭类型一样可访问”
  • 没错。如果ColorSlider 是公共的,那么您覆盖的任何方法也必须是公共的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-01
相关资源
最近更新 更多