ios - 约束不随设备方向变化而更新

标签 ios swift autolayout

我有一个 color slider在从标签延伸到单元格的 trailingAnchor 的 tableView 单元格中。我遇到的问题是当设备方向发生变化时,颜色 slider 不会更新其约束并且不再延伸单元格的全长。下面是我在颜色 slider 上设置约束的代码。以下是显示我遇到的问题的图片。如果我呈现此场景时我的手机已经处于横向,则颜色 slider 会根据需要扩展单元格的整个长度。但是,如果我在查看此场景时切换到横向,则 slider 将如下所示。这是 full code如果有帮助的话。

Slider Portrait Slider Landscape

  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/

相关文章:

ios - 如何在 ios 的 uiwebview 中水平滚动文档(pdf、ppt、docx)?

json - 需要帮助解码包含数组的 Json

ios - 为编程 View 层次结构设置自动布局约束?

ios - 如何将 SQLite 表导入 Core Data(SQLite 也是如此)

ios - Swift 将 UITextView 文本保存到 .Pdf、.Doc 和 .Txt 文件格式并显示

ios - 在 View Controller segue 之间传递数据

ios - 在一个 VC 上显示后重新设置 WKWebView

ios - 在 tableView 中添加填充功能 (Swift)

ios - 如何更改 userInterfaceLayoutDirection

ios - UIScrollView 嵌入导航 Controller 时表现不同