gpt4 book ai didi

ios - 如何使用自动布局在 Swift 中为可重用的 UIView 设置约束?

转载 作者:可可西里 更新时间:2023-11-01 01:40:02 25 4
gpt4 key购买 nike

我正在尝试构建一个可重用的 UIView,其宽度应等于其在 Swift 中的 super View 。

由于其父 View 的大小各不相同,我想我必须使用自动布局为其设置约束。

但我不知道如何在 Swift 中以编程方式执行此操作。

这是可重用 subview 的代码:

import UIKit

class bottomMenu: UIView {

@IBOutlet var bottomMenu: UIView!


required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
NSBundle.mainBundle().loadNibNamed("bottomMenu", owner: self, options: nil)

bottomMenu.backgroundColor = UIColor.redColor()

//How to make the width of the bottom Menu equal to its superview?

self.addSubview(self.bottomMenu)
}

}

谁能告诉我怎么做?

谢谢

最佳答案

您可以重写 UIView 子类中的 didMoveToSuperview() 方法并在其中添加约束:

    override func didMoveToSuperview() {
super.didMoveToSuperview()

backgroundColor = UIColor.redColor()

let views = ["view" : self];
self.setTranslatesAutoresizingMaskIntoConstraints(false)

self.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
self.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
}

关于ios - 如何使用自动布局在 Swift 中为可重用的 UIView 设置约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30706405/

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