2017-03-27 53 views
0

不幸的是,我被一個xib加載到滾動視圖中,它不像我期望的那樣運行。子視圖大小錯誤

除非我設置self.view.frame.size.height和self.view.frame.size.width,子視圖是錯誤的大小(太小)。

下面是似乎工作(水平模式)的值:

iPhone SE: 瓦特:1136 H:608 導航欄:32

iPhone 7: 瓦特: 1334 h:718 navbar:32

iPhone 7 Plus: 寬:1366 H:784 導航欄:44

iPad的9.7" : 寬:1366 H:980 導航欄:44

而不是硬編碼值,我寧願使用一種在運行時派生出的方法。我已經使用UIScreen.main.bounds.width/heightUIScreen.main.nativeBounds.width/height嘗試,但同時nativeBound適用於一些,正常的人似乎爲別人打工等

主視圖控制器代碼

let screenSize = UIScreen.main.bounds 
    let screenWidth = screenSize.width 
    let screenHeight = screenSize.height 
    let screenHeightWithoutBar = screenHeight - self.navigationController!.navigationBar.frame.height 



    var TopicsArray = [String](arrayLiteral: "Topic1","Topic2","Topic3","Topic4","Topic5") 
    var TopicItemArray = [TopicItemViewController]() 

    for i in 0..<TopicsArray.count { 

     let TopicItemVC :TopicItemViewController = TopicItemViewController(nibName: "TopicItemViewController", bundle: nil); 

     TopicItemVC.toPassTopicName = TopicsArray[i] 

     self.addChildViewController(TopicItemVC); 
     self.scrollView!.addSubview(TopicItemVC.view); 
     TopicItemVC.didMove(toParentViewController: self); 

     TopicItemArray.append(TopicItemVC) 
    } 

    var topicCounter = 1 
    for topicView in TopicItemArray { 

     if(topicCounter<TopicItemArray.count){ 
      var topicFrame :CGRect = screenSize; 

      topicFrame.origin.x = CGFloat(topicCounter) * screenWidth; 

      TopicItemArray[topicCounter].view.frame = topicFrame; 
     } 

     topicCounter += 1 
    } 

    let scrollWidth: CGFloat = CGFloat(TopicItemArray.count) * screenWidth 
    let scrollHeight: CGFloat = screenHeightWithoutBar 

    self.scrollView!.contentSize = CGSize(width: scrollWidth, height: scrollHeight); 

TopicItemViewController代碼

class TopicItemViewController: UIViewController { 


    override func viewDidLoad() { 
     super.viewDidLoad() 
     var screenScale: CGFloat = UIScreen.main.scale 
     //iphone 7 plus (nav is 44) 
     self.view.frame.size.height = 784 
     self.view.frame.size.width = 1366 

     //iphone 7 // same as resolution 
     //nav is 32 
     //self.view.frame.size.height = 718 //718+32 = 750 
     //self.view.frame.size.width = 1334 
    } 
    } 
+0

你不想使用原生界限。這是屏幕的物理像素大小,而不是歸化大小。 – TheValyreanGroup

+0

你在做什麼?顯示一些代碼,您正在加載視圖並嘗試設置其大小? – DonMag

+0

@DonMag我已經添加了代碼 – Phil

回答

0

所以經過大量的搜索和混亂,我已經解決了這個問題。

我確實可以擺脫硬編碼,因爲當我在viewDidLayoutSubviews而不是viewDidLoad中加載它時,正確的值被拾取!所有現有的約束條件都開始工作。在上面的例子中,它讓我刪除self.view.frame.size.heightself.view.frame.size.width