gpt4 book ai didi

ios - UIScrollView 页面宽度不等于 self.view 宽度

转载 作者:行者123 更新时间:2023-11-29 02:25:03 26 4
gpt4 key购买 nike

我有代码:

为什么 UIScrollView 的页面宽度不等于 self.view 宽度?

如果我认为正确,self.view.frame.size.width 必须等于 scroll.bounds.width 和 scroll.contentSize 必须是 self.view.frame.size.width*4(在这种情况下),是对吗?

非常感谢!!

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) 如果您要在一行之后设置框架,则无需设置边界,因此您可以完全删除这一行:scroll.bounds = self.view.bounds

(2) 将 viewDidLoad 中的所有其他内容移动到 viewDidLayoutSubviews,因为您设置的框架取决于 View 的宽度,这可以改变一个 subview 布局以适本地适合屏幕。但我也建议只使用条件执行此代码一次,因为 viewDidLayoutSubviews 可以多次调用,您应该只运行此代码一次,以免不必要地添加额外的 subview ,例如:

@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
}
}

关于ios - UIScrollView 页面宽度不等于 self.view 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27661571/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com