我有以下代码,它创建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
是不可见的。
标签和图像视图从第二个视图开始向右移动。
帧根据超级视图的坐标空间表示。
由于要向view
而不是滚动视图添加图像视图和标签,因此应在view
的坐标空间中指定它们的帧。因此,您无需将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
和自动布局,以获得更可靠的方法来实现这一目标。