gpt4 book ai didi

swift - 添加自动布局约束后,来自 NIB 的 UIView 不符合父约束

转载 作者:行者123 更新时间:2023-11-28 12:37:30 26 4
gpt4 key购买 nike

我正在使用 :

将我的 NIB 文件加载到我的 View 中
override init(frame: CGRect) {        
super.init(frame: frame)
Bundle.main.loadNibNamed("EventPopup", owner: self, options: nil)
//self.frame = self.view.bounds - DIDN'T WORK
//self.frame.size.width = 300 - DID'T WORK
self.addSubview(self.view); // adding the top level view to the view hierarchy
}

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
Bundle.main.loadNibNamed("EventPopup", owner: self, options: nil)
self.addSubview(self.view); // adding the top level view to the view hierarchy
}

这有效并添加了我的 NIB,但 UIView 的宽度延伸到了父容器之外。这仅在将自动布局添加到 uiview 后发生。我已经检查过,初始框架的尺寸为 600x600。

即使在尝试通过调用 layoutSubviews() 并在其中放置新的框架约束来重置 NIB 大小之后,它仍然拒绝调整大小。例如:

override func layoutSubviews() {
// self.frame.size.width = 300
//self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: 200, height: self.frame.height)
}

最佳答案

看看这篇文章here .查看第三个技巧,它展示了如何创建一个从 nib 加载的 View 。代码转载如下(免责声明它是用 Swift 2 编写的):

@IBDesignable
class ProfileView: UIView {
@IBOutlet var imgView: UIImageView!
@IBOutlet var labelOne: UILabel!
@IBOutlet var labelTwo: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
func setUp() {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: “Profile”, bundle: bundle)
let viewFromNib = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
addSubview(viewFromNib)
viewFromNib.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
“H:|[v]|”,
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: [“v”:viewFromNib]
)
)
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
“V:|[v]|”,
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil, views: [“v”:viewFromNib]
)
)
}
}

一旦您在代码和 nib 中正确设置了它,您应该能够轻松地对其进行初始化。在界面构建器或代码中:

// View Controller

override viewDidLoad() {
super.viewDidLoad()
self.addSubview(ProfileView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)))
}

关于swift - 添加自动布局约束后,来自 NIB 的 UIView 不符合父约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40450569/

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