2014-12-26 50 views
0

我有代碼:UIScrollView頁面寬度不等於self.view寬度

爲什麼UIScrollView的頁面寬度不等於self.view寬度?

如果我認爲正確,self.view.frame.size.width必須等於scroll.bounds.width且scroll.contentSize必須爲self.view.frame.size.width * 4(在這種情況下),這樣對嗎?

Thx很多!

class ViewController: UIViewController { 

    @IBOutlet weak var scroll: UIScrollView! 
    var frame: CGRect = CGRectMake(0, 0, 0, 0) 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     scroll.bounds = self.view.bounds 
     scroll.frame = self.view.frame 

     NSLog("%@", UIScreen.mainScreen().bounds.width); 
     NSLog("%@", scroll.bounds.width); 
       NSLog("%@", self.view.bounds.width); 
     NSLog("%@", scroll.contentSize.width); 


     let colors = [UIColor.redColor(), UIColor.greenColor(), UIColor.yellowColor(), UIColor.magentaColor()]; 

     for index in 0..<colors.count { 

      frame.origin.x = self.view.frame.size.width * CGFloat(index) 
      frame.size = self.view.frame.size 

      var subView = UIView(frame: frame) 
      subView.backgroundColor = colors[index] 
      subView.layer.borderColor = UIColor.blackColor().CGColor 
      subView.layer.borderWidth = 1.0; 
      self.scroll .addSubview(subView) 
     } 

     scroll.contentSize = CGSizeMake(self.view.frame.size.width * CGFloat(colors.count), self.view.frame.size.height)   
    } 
... 
} 

我在第二頁看到了什麼: enter image description here

回答

1

(1)有沒有必要設定的界限,如果你要一行稍後設置框架,這樣你就可以完全刪除此行:scroll.bounds = self.view.bounds

(2)將一切在你的viewDidLoadviewDidLayoutSubviews因爲你設置的框架依賴於視圖的寬度,可以改變一個子視圖已經奠定了適當地適應屏幕。不過,我還建議一次只使用一個條件,因爲viewDidLayoutSubviews執行該代碼可以被多次調用,你應該只運行一次該代碼,以免不必要地增加額外的子視圖,例如:

@IBOutlet weak var scroll: UIScrollView! 
var frame: CGRect = CGRectMake(0, 0, 0, 0) 
var viewLaidout:Bool = false 

override func viewDidLayoutSubviews() { 

    if !viewLaidout { 
     scroll.frame = self.view.frame 

     let colors = [UIColor.redColor(), UIColor.greenColor(), UIColor.yellowColor(), UIColor.magentaColor()]; 

     for index in 0..<colors.count { 

      frame.origin.x = self.view.frame.size.width * CGFloat(index) 
      frame.size = self.view.frame.size 

      var subView = UIView(frame: frame) 
      subView.backgroundColor = colors[index] 
      subView.layer.borderColor = UIColor.blackColor().CGColor 
      subView.layer.borderWidth = 1.0; 
      self.scroll.addSubview(subView) 
     } 

     scroll.contentSize = CGSizeMake(self.view.frame.size.width * CGFloat(colors.count), self.view.frame.size.height) 
     viewLaidout = true 
    } 
} 
+0

THX一個很多!你太棒了。是否因爲自動佈局而發生? – Costa

+1

很酷的解釋。謝謝 –