以编程方式快速创建水平 UIScrollView

Posted

技术标签:

【中文标题】以编程方式快速创建水平 UIScrollView【英文标题】:Create a horizontal UIScrollView in swift programmatically 【发布时间】:2018-03-28 04:36:19 【问题描述】:

我想知道如何在不使用情节提要的情况下通过页面控制器以编程方式快速创建水平滚动视图。

【问题讨论】:

check this & this 【参考方案1】:
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.
    

【讨论】:

【参考方案2】:

试试这个

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.
    



【讨论】:

以上是关于以编程方式快速创建水平 UIScrollView的主要内容,如果未能解决你的问题,请参考以下文章

如何以编程方式快速创建 uicollectionview(没有情节提要)

快速以编程方式创建后如何在情节提要中链接 UIButton

Segue 和 Button 以编程方式快速

如何使用 Objective-C 以编程方式使我的 UIView 可水平滚动?

使用内置 iOS 日历以编程方式快速创建日历/访问

以编程方式从子视图快速返回按键事件