【问题标题】:Wrong alignment of subviews in a UIScrollViewUIScrollView 中的子视图对齐错误
【发布时间】:2015-06-13 08:32:43
【问题描述】:

我有以下代码,它创建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)

它工作正常,除了第一个 viewimageViewtitleLabel 之外的事实不可见。

标签和 imageView 从第二个视图开始向右移动。

【问题讨论】:

    标签: ios objective-c swift uiview uiscrollview


    【解决方案1】:

    frames是根据superview的坐标空间来表达的。

    由于您将图像视图和标签添加到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 和自动布局以获得更可靠的实现方式。

    【讨论】:

      猜你喜欢
      • 2015-10-08
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多