以编程方式在swift中创建一个水平UIScrollView

时间:2018-03-28 04:36:20

标签: swift4

我想知道如何在不使用故事板的情况下以编程方式在swift中创建水平滚动视图,并使用页面控制器。

2 个答案:

答案 0 :(得分:1)

试试这个

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    var scrollView: UIScrollView!

    let textData: String = "Just to add onto the already great answers, you might want to add multiple labels in your project so doing all of this (setting size, style etc) will be a pain. To solve this, you can create a separate UILabel class."

    override func viewDidLoad() {
        super.viewDidLoad()

        let textLable = UILabel(frame: CGRect(x: 0, y: 0, width: 1000, height: 200))
        textLable.text = textData

        self.scrollView = UIScrollView()
        self.scrollView.delegate = self
        self.scrollView.contentSize = CGSize(width: textLable.frame.width, height: textLable.frame.height)

        scrollView.addSubview(textLable)
        view.addSubview(scrollView)

    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        scrollView.frame = view.bounds
    }

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


}

答案 1 :(得分:0)

import UIKit

class SecondViewController: UIViewController, UIScrollViewDelegate {

    var scrollview = UIScrollView()
    var imageview = UIImageView()
    var view1 = UIView()
    override func viewDidLoad() {
        super.viewDidLoad()
        imageview.frame = CGRect(x: 0, y: 0, width: view.frame.size.width , height: 1000)
         imageview.image = UIImage(named: "image")
        scrollview.delegate = self
        scrollview.contentSize = CGSize(width: imageview.frame.width, height: imageview.frame.height)


        scrollview.backgroundColor = UIColor.red
        imageview.backgroundColor =  UIColor.green

        self.scrollview.addSubview(imageview)
        view.addSubview(scrollview)
        scrollview.translatesAutoresizingMaskIntoConstraints = false



        scrollview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        scrollview.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
        scrollview.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        scrollview.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true


        // Do any additional setup after loading the view.
    }