UIScrollView 中的子视图对齐错误
Wrong alignment of subviews in a UIScrollView
我有以下代码,它创建 UIView
及其一些子视图,并将它们添加到 UIScrollView
,全部在一个循环中:
var count:CGFloat=bookScrollView.frame.minX
for var i=0;i<10;i++ {
var view=UIView(frame: CGRect(x: count + 20, y: bookScrollView.frame.minY + 30, width: 200, height: 300))
view.backgroundColor=UIColor.whiteColor()
view.layer.cornerRadius = 5;
view.layer.masksToBounds = true;
var imageView=UIImageView(frame: CGRect(x: count, y: view.frame.minY - 30, width: 150, height: 220))
// imageView.image=UIImage(named: "Sample_Book")!
view.addSubview(imageView)
var titleLabel=UILabel(frame: CGRect(x: count + 10, y: imageView.frame.maxY + 30, width: 185, height: 60))
titleLabel.text="Head First Javascript"
titleLabel.backgroundColor=UIColor.clearColor()
titleLabel.font=UIFont(name: "Menlo-Bold ", size: 15)
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.textColor=UIColor.grayColor()
view.addSubview(titleLabel)
bookScrollView.addSubview(view)
count+=220
}
bookScrollView.contentSize=CGSize(width: count, height: 200)
它工作正常,除了第一个 view
、imageView
和 titleLabel
之外的事实是不可见的。
标签和图像视图从第二个视图开始向右移动。
帧是根据superview的坐标表示的 space.
由于您要将图像视图和标签添加到 view
而不是滚动视图,因此它们的框架应该在 view
的坐标 space 中指定。所以你不需要添加 count
到他们的 x 位置。
var imageView=UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: 150, height: 220))
并且:
var titleLabel=UILabel(frame: CGRect(x: 10.0, y: imageView.frame.maxY + 30, width: 185, height: 60))
注意: 您应该研究 UICollectionView
和自动布局以获得更可靠的实现方式。
我有以下代码,它创建 UIView
及其一些子视图,并将它们添加到 UIScrollView
,全部在一个循环中:
var count:CGFloat=bookScrollView.frame.minX
for var i=0;i<10;i++ {
var view=UIView(frame: CGRect(x: count + 20, y: bookScrollView.frame.minY + 30, width: 200, height: 300))
view.backgroundColor=UIColor.whiteColor()
view.layer.cornerRadius = 5;
view.layer.masksToBounds = true;
var imageView=UIImageView(frame: CGRect(x: count, y: view.frame.minY - 30, width: 150, height: 220))
// imageView.image=UIImage(named: "Sample_Book")!
view.addSubview(imageView)
var titleLabel=UILabel(frame: CGRect(x: count + 10, y: imageView.frame.maxY + 30, width: 185, height: 60))
titleLabel.text="Head First Javascript"
titleLabel.backgroundColor=UIColor.clearColor()
titleLabel.font=UIFont(name: "Menlo-Bold ", size: 15)
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.textColor=UIColor.grayColor()
view.addSubview(titleLabel)
bookScrollView.addSubview(view)
count+=220
}
bookScrollView.contentSize=CGSize(width: count, height: 200)
它工作正常,除了第一个 view
、imageView
和 titleLabel
之外的事实是不可见的。
标签和图像视图从第二个视图开始向右移动。
帧是根据superview的坐标表示的 space.
由于您要将图像视图和标签添加到 view
而不是滚动视图,因此它们的框架应该在 view
的坐标 space 中指定。所以你不需要添加 count
到他们的 x 位置。
var imageView=UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: 150, height: 220))
并且:
var titleLabel=UILabel(frame: CGRect(x: 10.0, y: imageView.frame.maxY + 30, width: 185, height: 60))
注意: 您应该研究 UICollectionView
和自动布局以获得更可靠的实现方式。