【问题标题】:Adding View Controllers side by side into a Scroll View将视图控制器并排添加到滚动视图中
【发布时间】:2017-04-02 19:08:16
【问题描述】:

如何将现有的视图控制器添加到滚动视图中。我已经在“viewDidLoad”中尝试了下面的代码,但它没有用。谢谢

let view1 = ViewController6()
        let view2 = ViewController2()
        let view3 = ViewController3()

        contentView.addSubview(view1)
        contentView.addSubview(view2)
        contentView.addSubview(view3)

        self.contentView.contentSize = CGSize(width: self.view.frame.width * 3, height: self.view.frame.height)

【问题讨论】:

  • 查看容器视图。这个想法是您创建一个 contentView (UIView),将子 UIViewControllers 添加到您当前的 ViewController,然后将子 ViewController 的视图添加到内容视图中。

标签: ios swift uiviewcontroller uiscrollview


【解决方案1】:

检查此代码在这里我正在做你想要实现的事情。

func setupScrollView()
    {
        //loop for 
        for i in 0..<3 {
            //we instantiate our viewController from storyboard
            let news2 = self.storyboard?.instantiateViewController(withIdentifier: "NewsMasterViewController") as! NewsMasterViewController
            //we adjust the frame according
            news2.view.frame = CGRect(x: CGFloat(i) * self.scrollView.frame.size.width + CGFloat(MasterViewController.margin), y: 0, width: self.scrollView.frame.size.width - CGFloat(MasterViewController.margin * 2), height: self.scrollView.frame.size.height)
            //we call layoutSubviews for constraints adjustments
            news2.view.layoutSubviews()
            self.addChildViewController(news2)
            //added the view of my viewController "news2" to scrollView
            self.scrollView.addSubview(news2.view)
            news2.didMove(toParentViewController: self)
            //added the viewController "news2" to my array of viewControllers
            newsMasterViewControllers.append(news2)
        }

        //adjusted contentSize of scrollView according the number of viewControllers added
        self.scrollView.contentSize = CGSize(width: self.view.frame.size.width * 3, height: self.scrollView.frame.size.height);
    }

希望对你有帮助

【讨论】:

  • 如果去掉 .didMove 方法,scrollView 将不再移动。所以,干得好,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-05
  • 2014-12-18
  • 2016-01-03
  • 1970-01-01
相关资源
最近更新 更多