gpt4 book ai didi

ios - 自定义创建的 View 大小不会根据约束发生变化

转载 作者:行者123 更新时间:2023-11-28 13:52:14 24 4
gpt4 key购买 nike

我构建了一个自定义 View ,需要嵌入到不同的地方。

这是我对代码所做的:

1) 创建了一个 Swift 文件和一个名为 CustomLabel 的 xib 文件。 CustomLabel.swift 的内容:

import UIKit

class CustomLabel: UIView {

@IBOutlet var view: UIView!
@IBOutlet weak var label: UILabel!

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print("CustomLabel")
Bundle.main.loadNibNamed("CustomLabel", owner: self, options: nil)


self.addSubview(self.view)
}



}

CustomLabel.xib 的外观如下:

I have made the size

我已将 View 设为自由形式并设置其高度。我在其中添加了一个标签 View ,在所有四个方面都有约束。

现在我将此 View 添加到我的主视图 Controller ,但将此 View 的宽度设置为大于原始可重用 View 。

这是结果:

enter image description here

黄色背景显示 View 的额外宽度,黑色背景是原始 View 。

如何确保可重用 View 被拉伸(stretch)以覆盖整个 View ?

最佳答案

您加载 XIB 的方式创建了两个 UIView 对象,而您可能认为它只创建了一个。

您可以使用 Debug View Hierarchy 轻松查看此内容

这里,蓝色 View 是添加到 Storyboard 的 View ,具有正常的约束设置(在本例中,每边 40 磅,高度 100,垂直居中)。

红色 View 是您在设计 XIB 时使用的 View ,它有一个黑色背景的标签,所有四个边都被限制为 0

enter image description here

您的 XIB UIView —— 所以它是它的自己的 View ...当您添加一个UIView 到您的 Storyboard 并将其类设置为 CustomLabel,这将成为“根” View 。在您的代码中,您正在添加 view 作为 subview ...这应该给您提示您现在有两个 UIView 对象。

现在发生的事情是 CustomLabel 本身(它是一个 UIView)使用您在 Storyboard 中设置的约束,但是 view subview 没有设置约束。

如果您将加载代码更改为此(我更改了您的 IBOutlet 名称,因为将“view”作为 subview 添加到另一个“view”会变得非常困惑):

class CustomLabel: UIView {

@IBOutlet var theView: UIView!
@IBOutlet weak var thelabel: UILabel!

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print("CustomLabel")
Bundle.main.loadNibNamed("CustomLabel", owner: self, options: nil)

self.addSubview(self.theView)

self.theView.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
self.theView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0.0),
self.theView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0.0),
self.theView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0.0),
self.theView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0.0),
])

}

}

现在,您的代码从 XIB 加载 View ,将其添加为 CustomLabel 的 subview (它本身也是一个 UIView),并设置如你所料的约束,给出这个结果:

enter image description here

如您所见,已添加为 subview (此图中的红色)的 theView 现在受限于其父 View - 蓝色 CustomLabel

关于ios - 自定义创建的 View 大小不会根据约束发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54402813/

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