在Storyboard中使用PageControl进行ScrollView

时间:2017-12-13 08:06:42

标签: ios swift uiscrollview uipagecontrol

我有三个图表,我希望能够在滚动视图中滚动页面控件,我想知道设置它的最佳方法是什么。我见过的大多数教程都以编程方式设置了视图,但为了使用图表我必须在故事板中创建UIViews,所以我想知道设置scrollView的最佳方法是什么这样每个图表都在一个单独的页面上?

enter image description here

相关的代码行如下。我是否需要在其他地方拖动包含图表的UIViews?或者不能在故事板上完成?

import UIKit
import Charts

class ChartsViewController: UIViewController {

    // MARK: Types

    enum TimePeriod: Int {
        case day = 0
        case week = 1
        case month = 2
        case year = 3
    }

    // MARK: Properties

    var period: TimePeriod = .day {
        didSet {
            print(self.period)
        }
    }

    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var pieChart: PieChartView!
    @IBOutlet weak var segmentedControl: UISegmentedControl!
    @IBOutlet weak var barChart: BarChartView!
    @IBOutlet weak var lineChart: LineChartView!

    func lineChartUpdate() {
        var lineChartEntry = [ChartDataEntry]()
        for i in 0 ..< 15 {
            let value = ChartDataEntry(x: Double(i), y: Double(i))
            lineChartEntry.append(value)
        }
        let line1 = LineChartDataSet(values: lineChartEntry, label: "Category 1")
        let data = LineChartData(dataSets: [line1])
        lineChart.data = data
        lineChart.chartDescription?.text = "Line Chart"

        lineChart.notifyDataSetChanged()
    }

    func configurePageControl() {
        self.pageControl.numberOfPages = 3
        self.pageControl.currentPage = 0
    }

    @IBAction func renderCharts(_ sender: UISlider) {
        pieChartUpdate()
        barChartUpdate()
    }

    @IBAction func segmentedControlSelectedIndexDidChange(_ sender: UISegmentedControl) {
        self.period = TimePeriod(rawValue: sender.selectedSegmentIndex)!
    }

    // MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        configurePageControl()
        pieChartUpdate()
        barChartUpdate()
        lineChartUpdate()
        scrollView.addSubview(pieChart)
        scrollView.addSubview(barChart)
        scrollView.addSubview(lineChart)
    }

    @IBAction func pageChange(_ sender: UIPageControl) {

    }


}

1 个答案:

答案 0 :(得分:0)

您可以在xib中创建视图,然后以编程方式在scrollview中添加。

示例:

你有三个观点。

厂景

视图2

视图2

您可以将它们添加到scrollview中:

override func viewDidLoad() {
    super.viewDidLoad() 
    view1 = View1(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
    scrollView.addSubview(view1!)
    view2 = View2(frame: CGRect(x: UIScreen.main.bounds.width, y: 0, width: UIScreen.main.bounds.width, height: 522))
    scrollView.addSubview(view2!)
    view3 = View3(frame: CGRect(x: UIScreen.main.bounds.width*2, y: 0, width: UIScreen.main.bounds.width, height: height))
    scrollView.addSubview(view3!)
}