使用UIView作为子视图的水平分页的UIScrollView

时间:2017-07-13 17:33:37

标签: ios uiview swift3 uiscrollview subviews

我已经看到了以下问题的答案。我是快速编程的新手,我正在尝试实现类似的功能。我只是想知道你是否有关于如何在swift 3 Xcode 8中实现这一目标的任何指导。我一直在寻找合适的解决方案,但我没有运气。

我正在尝试使用UIViews作为UIscrollviews的子视图。我还希望每个视图在按下时填满屏幕并显示另一个UIView。我在“Tyler the Creator”中看到了GOLF应用程序中的类似功能

我正在尝试实现的功能如下图所示。

非常感谢您给予的任何帮助。

这是我试图创建的功能的表示。

image

2 个答案:

答案 0 :(得分:1)

    let scrollView : UIScrollView = UIScrollView(frame: CGRect(x: 80, y: 80, 
    width: 250, height: 300))
    scrollView.isPagingEnabled = true
    scrollView.backgroundColor = .orange
    view.addSubview(scrollView)
    let numberOfPages :Int = 5
    let padding : CGFloat = 15
    let viewWidth = scrollView.frame.size.width - 2 * padding
    let viewHeight = scrollView.frame.size.height - 2 * padding

    var x : CGFloat = 0

    for i in 0...numberOfPages{
        let view: UIView = UIView(frame: CGRect(x: x + padding, y: padding, width: viewWidth, height: viewHeight))
        view.backgroundColor = UIColor.white
        scrollView .addSubview(view)

        x = view.frame.origin.x + viewWidth + padding
    }

    scrollView.contentSize = CGSize(width:x+padding, height:scrollView.frame.size.height)

答案 1 :(得分:1)

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!

var colors:[UIColor] = [.red, .blue, .green, .yellow]
var frame: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
override func viewDidLoad() {
    super.viewDidLoad()

    scrollView.isPagingEnabled = true
    scrollView.backgroundColor = .orange
    view.addSubview(scrollView)
    let numberOfPages :Int = 3
    let padding : CGFloat = 15
    let viewWidth = scrollView.frame.size.width - 2 * padding
    let viewHeight = scrollView.frame.size.height - 2 * padding

    var x : CGFloat = 0

    for i in 0...numberOfPages{
        let view: UIView = UIView(frame: CGRect(x: x + padding, y: padding, width: viewWidth, height: viewHeight))
        view.backgroundColor = colors[i]
        scrollView .addSubview(view)
        x = view.frame.origin.x + viewWidth + padding
    }

    scrollView.contentSize = CGSize(width:x+padding, height:scrollView.frame.size.height)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}