如何使UIScrollview一次只显示一个子视图

时间:2017-01-21 20:55:47

标签: ios swift xcode uiscrollview swift3

我遵循了一个教程:https://www.youtube.com/watch?v=1_daE3IL_1s教你如何在swift 3中进行像聊天一样的菜单,每次你刷新一个子视图都放在屏幕上,但它是唯一一个你需要再刷一次才能获得下一个视图。这个教程是在swift 2中制作的,但是当我更新到swift 3时,scrollview现在表现得像普通的滚动视图,它可以流畅地滚动。有没有办法解决这个问题?

主视图控制器的代码:

class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let V1: View1 = View1(nibName: "View1", bundle: nil)
        let V2: View2 = View2(nibName: "View2", bundle: nil)
        let V3: View3 = View3(nibName: "View3", bundle: nil)

        V1.didMove(toParentViewController: self)
        self.addChildViewController(V1)
        self.scrollView.addSubview(V1.view)

        V2.didMove(toParentViewController: self)
        self.addChildViewController(V2)
        self.scrollView.addSubview(V2.view)

        V3.didMove(toParentViewController: self)
        self.addChildViewController(V3)
        self.scrollView.addSubview(V3.view)

        var V2Frame: CGRect = V2.view.frame
        V2Frame.origin.x = self.view.frame.width
        V2.view.frame = V2Frame

        var V3Frame: CGRect = V3.view.frame
        V3Frame.origin.x = 2 * self.view.frame.width
        V3.view.frame = V3Frame

        self.scrollView.contentSize = CGSize(width: self.view.frame.width*3 , height: self.view.frame.size.height)
    }

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

}

1 个答案:

答案 0 :(得分:3)

启用分页:

override func viewDidLoad() {
    super.viewDidLoad()
    scrollView.isPagingEnabled = true
    // ...
}