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

标签 ios swift uiview autolayout constraints

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

由于其 super 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/

相关文章:

ios - 仅在最近没有崩溃时才显示 SKStoreReviewController?

ios - 尝试使用 Alamofire 在 Swift 3 中解析 JSON

ios - 如何使用 Objective-C 在工具栏中显示图像

swift - 为什么非可选的 Any 可以容纳 nil?

swift - 串行队列内的并发队列调用?

iphone - 渲染 View ,缩放@2x,renderInContext,iPhone

iphone - 尝试在 uilabel 上设置背景颜色动画以实现 'fade' 效果,但它会立即应用

ios - 将日期从一种格式转换为其他格式在 objective-c 中返回 nil

ios - 点击后退按钮时隐藏搜索栏

ios - 如何根据顶部正面图像裁剪图像?