如何在SWIFT中将视图添加到容器视图中

时间:2015-08-18 00:47:45

标签: ios swift

现在我在这个视图中让我的ScrollView有一个包含unoView的容器,但这在顶部仍然是静态的。我想在ContainerView中围栏,希望有人可以帮助我。谢谢!

import UIKit

extension UIColor {
    static func fromUInt(rgbValue: UInt32) -> UIColor{
        let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 256.0
        let green = CGFloat((rgbValue & 0xFF00) >> 8) / 256.0
        let blue = CGFloat(rgbValue & 0xFF) / 256.0
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
}

class ViewController: UIViewController, UIScrollViewDelegate {

    var scrollView = UIScrollView()
    var containerView = UIView()
    var unoView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        scrollView.delegate = self
        containerView.backgroundColor = UIColor.fromUInt(0x0099FF)
        unoView.backgroundColor = UIColor.purpleColor()

        containerView.setTranslatesAutoresizingMaskIntoConstraints(false)
        scrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
        unoView.setTranslatesAutoresizingMaskIntoConstraints(false)

        view.addSubview(scrollView)
        scrollView.addSubview(containerView)
        view.addSubview(unoView)

        let viewsDictionary = ["scrollView": scrollView, "unoView": unoView]

        let view_constraint_H = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[scrollView]-0-|",
            options: NSLayoutFormatOptions(0),
            metrics: nil,
            views: viewsDictionary)

        let view_constraint_V = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[scrollView]-0-|",
            options: NSLayoutFormatOptions(0),
            metrics: nil,
            views: viewsDictionary)

        view.addConstraints(view_constraint_H)
        view.addConstraints(view_constraint_V)

        let view_constraintUno_H = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[unoView]-|",
            options: NSLayoutFormatOptions(0),
            metrics: nil,
            views: viewsDictionary)

        let view_constraintUno_V = NSLayoutConstraint.constraintsWithVisualFormat("V:|-25-[unoView(200)]-|",
            options: NSLayoutFormatOptions(0),
            metrics: nil,
            views: viewsDictionary)

        view.addConstraints(view_constraintUno_H)
        view.addConstraints(view_constraintUno_V)





        containerView.frame = CGRectMake(0, 0,  view.frame.width, 2000)
        scrollView.contentSize = containerView.frame.size
    }
}

1 个答案:

答案 0 :(得分:0)

你说容器包含unoView,但你写的是view.addSubview(unoView) - 那么,它不应该是containerView.addSubview(unoView)吗?

我不确定你在ContainerView'中的击剑是什么意思。你能详细说明你想在这里实现什么类型的布局吗?