ios - Autolayout - UIView 不能正确调整到 subview 的大小

标签 ios swift uiview autolayout uilabel

我正在尝试使用自动布局以编程方式创建一个 UIView 并将 UILabel 作为 subview 。

约束

我在 view 上使用了以下约束:

    view
  • CenterXfastAttacksContainerView (superview)

  • 常量 8 对父 View 的上层约束。

  • 然后创建一个 label,它是 view 的 subview ,并为 TopBottom 添加常量 8 的约束查看

问题

view 仅根据标签的frame 调整大小,不考虑所有 4 个边上常量 8 的 4 个约束。这会导致 label 部分显示在 view 之外。

let view = UIView()
view.backgroundColor = pokemon.secondaryColor

let label = UILabel()

fastAttacksContainerView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false

view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false

label.text = fa

let gest = UITapGestureRecognizer(target: self, action: #selector(self.selectFastAttack))
view.addGestureRecognizer(gest)

fastAttackButtons.append(view)
fastAttackLables.append(label)

let top = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: fastAttacksContainerView, attribute: .Top, multiplier: 1, constant: 8)
let centerX = NSLayoutConstraint(item: view, attribute: .CenterX, relatedBy: .Equal, toItem: fastAttacksContainerView, attribute: .CenterX, multiplier: 1, constant: 0)

let labLeft = NSLayoutConstraint(item: label, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 8)
let labTop = NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 8)
let labRigth = NSLayoutConstraint(item: label, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 8)
let labBottom = NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 8)
view.addConstraints([labLeft, labTop, labRigth, labBottom])
fastAttacksContainerView.addConstraints([top, centerX])

输出

Simulation

最佳答案

view 高度不明确。

您应该为 view 的高度或它到 fastAttacksContainerView 底部的距离添加约束。

关于ios - Autolayout - UIView 不能正确调整到 subview 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38937479/

相关文章:

ios - 我的 iPhone 应用程序应该占用多少内存?

ios - 将在代码中创建一个 View ,如何在 Swift 1.2 中声明 int

ios - 数组自发清空

ios - 将 ViewController 缩小为圆形过渡 - swift

ios - 更新配置文件和证书

ios - 段错误 : 11 - Xcode/Swift 5 compile issue

ios - 如何在单击下一个按钮时播放下一首歌曲

ios - 如何生成包含尺寸大于设备屏幕的 View 的 PDF?

另一个 View 范围内的 iOS View

objective-c - 什么是 Controller 类?