UIStackView编程充满UIViews里面的UIScrollView不滚动

问题描述 投票:0回答:2

我还是个SO和斯威夫特新手,所以,请耐心等待:-)

我有一个UIViewController

这里面viewcontroller有一个UIScrollView

所述UIScrollView内部有一个UIStackView(在0,0,0,0与AutoLayout钉扎和垂直和水平中心的),具有水平轴线。

我的目标是子视图添加到stackview,使滚动视图滚动水平。

所以,我做了以下内容:

import UIKit

    class ViewController: UIViewController, UIScrollViewDelegate {

        @IBOutlet weak var scroller: UIScrollView!
        @IBOutlet weak var stack: UIStackView!

        override func viewDidLoad() {

            super.viewDidLoad()
            scroller.delegate = self

            for i in 0..<10 {

                let customView = UIView(frame: CGRect(x: 0, y: 0, width: 240, height: 128))
                // .random is unimportant here
                customView.backgroundColor = .random()
                stack.addArrangedSubview(customView)

            }

        }

        override func viewDidLayoutSubviews(){
            self.scroller.contentSize = CGSize(width:2400,height:128)
            print(self.scroller.contentSize) // 2400
            print(self.stack.subviews)
        }

        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            print("scrollin'")
        }


    }

问题是,有些事情我必须失去,因为滚动视图完全不滚动。我只看到一个观点(当然,随时随地用不同的颜色)。

我敢肯定的意见被加载,因为这是第二次打印输出:

[<UIView: 0x159e01a10; frame = (0 0; 240 128); layer = <CALayer: 0x28115d7a0>>, <UIView: 0x159e03f10; frame = (0 0; 240 128); layer = <CALayer: 0x28115d800>>, <UIView: 0x159e046d0; frame = (0 0; 240 128); layer = <CALayer: 0x28115d960>>, <UIView: 0x159e0e410; frame = (0 0; 240 128); layer = <CALayer: 0x28115da80>>, <UIView: 0x159e0e7c0; frame = (0 0; 240 128); layer = <CALayer: 0x28115db20>>, <UIView: 0x159e0e9a0; frame = (0 0; 240 128); layer = <CALayer: 0x28115da60>>, <UIView: 0x159e0eb80; frame = (0 0; 240 128); layer = <CALayer: 0x28115dbe0>>, <UIView: 0x159e0ed60; frame = (0 0; 240 128); layer = <CALayer: 0x28115dc80>>, <UIView: 0x159e0ef40; frame = (0 0; 240 128); layer = <CALayer: 0x28115dd20>>, <UIView: 0x159e0f120; frame = (0 0; 240 128); layer = <CALayer: 0x28115ddc0>>]

那么,什么是它发生?为什么滚动视图不滚动?

ios swift uiview uiscrollview
2个回答
-1
投票

试试这个代码,我希望它可以帮助你。

override func viewDidLoad() {

    super.viewDidLoad()
    scroller.delegate = self

        for i in 0..<10 {
            let xPosition = 240 * CGFloat(i)
            let customView = UIView(frame: CGRect(x: xPosition, y: 0, width: 240, height: 128))
            // .random is unimportant here
            customView.backgroundColor = .random()
            scroller.addSubview(customView)
        }
    scroller.contentSize.width = 2400
}

-1
投票

替换此

  let customView = UIView(frame: CGRect(x: 0, y: 0, width: 240, height: 128))

let customView = UIView(frame: CGRect(x: CGFloat( i * 240 ) , y: 0, width: 240, height: 128))

我认为没有必要为stackView,和

scroller.addSubview(customView)

看看这个Scroller

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.