我无法让UIScrollView与UIStackView一起使用

时间:2015-09-10 07:24:38

标签: ios swift uiscrollview uistackview

我正在尝试使StackView内容可滚动。我插入虚拟UIImage视图,试图让它工作,但它不滚动。堆栈和滚动视图已连接到IB。我错过了什么?

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var menuStackView: UIStackView!
    @IBOutlet weak var menuScrollView: UIScrollView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        var itemImageView = UIImageView(image: UIImage(named: "splash2"))
        itemImageView.contentMode = .ScaleAspectFit
        self.menuStackView.addArrangedSubview(itemImageView)

        itemImageView = UIImageView(image: UIImage(named: "splash2"))
        itemImageView.contentMode = .ScaleAspectFit
        self.menuStackView.addArrangedSubview(itemImageView)

        itemImageView = UIImageView(image: UIImage(named: "splash2"))
        itemImageView.contentMode = .ScaleAspectFit
        self.menuStackView.addArrangedSubview(itemImageView)

        itemImageView = UIImageView(image: UIImage(named: "splash2"))
        itemImageView.contentMode = .ScaleAspectFit
        self.menuStackView.addArrangedSubview(itemImageView)

        itemImageView = UIImageView(image: UIImage(named: "splash2"))
        itemImageView.contentMode = .ScaleAspectFit
        self.menuStackView.addArrangedSubview(itemImageView)

        itemImageView = UIImageView(image: UIImage(named: "splash2"))
        itemImageView.contentMode = .ScaleAspectFit
        self.menuStackView.addArrangedSubview(itemImageView)

        itemImageView = UIImageView(image: UIImage(named: "splash2"))
        itemImageView.contentMode = .ScaleAspectFit
        self.menuStackView.addArrangedSubview(itemImageView)


        itemImageView = UIImageView(image: UIImage(named: "splash2"))
        itemImageView.contentMode = .ScaleAspectFit
        self.menuStackView.addArrangedSubview(itemImageView)


    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        menuScrollView.contentSize = CGSize(width: menuStackView.frame.width, height: menuStackView.frame.height)

    }
}

1 个答案:

答案 0 :(得分:2)

我的想法是创建一个用你设置你的滚动视图的UIView。然后将堆栈视图添加到该内容视图。因为否则,为了使stackview像你想要的那样工作,我不得不在滚动视图的所有边上添加约束并添加高度和宽度约束。

我也在这里回答了一个类似的问题,可能有所帮助:

https://stackoverflow.com/a/32999501/4626443

这是指向一个带有滚动堆栈视图的项目的链接,您可以使用它来重新开始:

https://github.com/Rnorback/ScrollingStackView