gpt4 book ai didi

ios - UIImageView 上的宽度和高度 NSLayoutConstraints 不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 06:05:55 24 4
gpt4 key购买 nike

我正在我的 View Controller 的 updateViewConstraints() 中的 UIImgeView 实例上设置 .Width 和 .Top NSLayoutConstraints。在 XCode 可视化调试器中,我可以看到约束实际上已设置,但由于某种原因它们未被使用(?)它们显示为未(内容大小)并且显示为灰色。当我使用 NSLog 输出约束时,我也可以看到它们已设置,但不知何故图像保持原始大小...... 这是什么意思?

constraints in parent: [<NSLayoutConstraint:0x7b379590 UIImageView:0x7af897b0.centerX == UIView:0x7b37d2e0.centerX>, 
<NSLayoutConstraint:0x7b36e3d0 V:|-(0)-[UIImageView:0x7af897b0] (Names: '|':UIView:0x7b37d2e0 )>]
constraints in view: [<NSContentSizeLayoutConstraint:0x7ae892b0 H:[UIImageView:0x7af897b0(301)] Hug:251 CompressionResistance:750>,
<NSContentSizeLayoutConstraint:0x7ae834e0 V:[UIImageView:0x7af897b0(365)] Hug:251 CompressionResistance:750>]

enter image description here

设置约束的代码:

/// Image view with the character + ellipse
@IBOutlet weak var charImageView: UIImageView!

override func updateViewConstraints() {
super.updateViewConstraints()
charImageView.widthLayoutConstraint?.constant = 301.0
charImageView.heightLayoutConstraint?.constant = 365.0
}

我用来获取 widthLayoutConstraintheightLayoutConstraint 的扩展

extension UIView{
/**
Gets the width layout constraint defined as the NSLayoutConstraint whose first item is self and first attribute is Height
*/
var heightLayoutConstraint:NSLayoutConstraint? {
get{
for constraint in constraints {
if constraint.firstItem as? UIView == self &&
constraint.firstAttribute == NSLayoutAttribute.Height
{
return constraint
}
}
return nil
}
}

/**
Gets the width layout constraint defined as the NSLayoutConstraint whose first item is self and first attribute is Width
*/
var widthLayoutConstraint:NSLayoutConstraint? {
get{
for constraint in constraints {
if constraint.firstItem as? UIView == self &&
constraint.firstAttribute == NSLayoutAttribute.Width
{
return constraint
}
}
return nil
}
}
}

这是最初使用 IB 添加布局约束的方式。如您所见,它们是为 Compact Width size Class 添加的,我在看到问题时正在使用它(iPhone4S 模拟器)。

约束已经通过 IB 添加,我正在用代码更新它们的常量。调试器清楚地显示常量实际上已更新,但不知何故图像以原始大小绘制。

enter image description here enter image description here

最佳答案

灰色约束表示这些约束存在但未安装在您的 View 中。

引用下图:

enter image description here

  1. 选择灰色约束
  2. 打开属性检查器
  3. 在底部你可以看到Installed选项
  4. 如果未选中,则单击复选标记启用它
  5. 这将在您的 View 中安装选定的约束

更新:

您可以使用以下代码添加width 约束:

self.addConstraint(NSLayoutConstraint(
item: charImageView,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: 301.0))

您可以使用我的其他答案更新约束值:

Update constraint's constant value programatically

关于ios - UIImageView 上的宽度和高度 NSLayoutConstraints 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37592337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com