2014-12-26 46 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

很酷的解释。谢谢 –