簡體   English   中英

UIPageViewController和AutoLayout:約束未正確應用

[英]UIPageViewController and AutoLayout: constraints are not applied correctly

我以編程方式創建一個UIPageViewController並將其作為子項添加到我的容器視圖控制器中,如下所示:

    override func viewDidLoad() {
    super.viewDidLoad()

    self.pageViewController = UIPageViewController(transitionStyle:.PageCurl, navigationOrientation:.Horizontal, options: nil)

    self.mainImageView!.userInteractionEnabled = true

    self.pageViewController.delegate = self
    self.pageViewController.dataSource = self.modelController

    self.addChildViewController(self.pageViewController)
    self.view.addSubview(self.pageViewController.view)

    self.pageViewController.didMoveToParentViewController(self)

}        

問題是UIPageViewController的視圖大小不正確,如下面的視圖層次結構所示。 UIPageViewController的數據源返回的視圖控制器包含單個UIScrollView 我已經設置了UIScrollView的約束,以便scrollView擴展到superview。

在我看來,問題源於scrollView約束與容器視圖的約束“分離”的事實,但我不知道如何使用StoryBoard修復它,因為這些是不同視圖控制器中的視圖。 我不是很熟悉以編程方式指定約束,到目前為止,我以編程方式設置約束的努力都失敗了。

如何解決這個問題,以便UIPageViewController的視圖控制器的滾動視圖正確包含在容器ViewController的視圖中?

在此輸入圖像描述

在此輸入圖像描述

我必須以編程方式添加約束來解決問題。 請注意,我無法使用IB添加自動布局約束,因為這里我處理的是屬於IB中兩個不同視圖控制器的兩個視圖。 視圖以編程方式添加為子視圖,因為它們是UIPageViewController視圖。

    override func viewDidLayoutSubviews() {
    self.pageViewController.view.setTranslatesAutoresizingMaskIntoConstraints(false)

    // Equal height constraint
    let constraint = NSLayoutConstraint(item: self.mainImageView!, attribute: .Height, relatedBy: .Equal, toItem: self.pageViewController.view, attribute: .Height, multiplier: 1.0, constant: 0)
    self.view.addConstraint(constraint)

    // Equal width constraint
    let constraint1 = NSLayoutConstraint(item: self.mainImageView!, attribute: .Width, relatedBy: .Equal, toItem: self.pageViewController.view, attribute: .Width, multiplier: 1.0, constant: 0)
    self.view.addConstraint(constraint1)

    // Equal top constraint
    let constraint2 = NSLayoutConstraint(item: self.mainImageView!, attribute: .Top, relatedBy: .Equal, toItem: self.pageViewController.view, attribute: .Top, multiplier: 1.0, constant: 0)
    self.view.addConstraint(constraint2)

    self.view.layoutSubviews()
}

我有同樣的問題,它已通過在viewDidLoad()添加以下代碼解決

pageViewController!.view.setTranslatesAutoresizingMaskIntoConstraints(false)
    let views = ["pageView": pageViewController!.view]

    var constH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[pageView]|", options: .AlignAllCenterY, metrics: nil, views: views)
    view.addConstraints(constH)
    var constW = NSLayoutConstraint.constraintsWithVisualFormat("V:|[pageView]|", options: .AlignAllCenterX, metrics: nil, views: views)
    view.addConstraints(constW)

我希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM