问题是,如何使这个空间更近?

ios - 如何使这个垂直空间更紧密?-LMLPHP

这是我的代码:

class ViewController: UIViewController
{
    @IBOutlet var mainScrollView: UIScrollView!
    var imageArray = [UIImage]()

    override func viewDidLoad()
    {
        super.viewDidLoad()

        mainScrollView.frame = view.frame
        imageArray = ["tumblr1","tumblr3","tumblr2","tumblr4","tumblr5"]

        for i in 0..<imageArray.count
        {
            let imageView = UIImageView()
            imageView.image = imageArray[i]
            imageView.contentMode = .scaleAspectFit

            let yPosition = self.view.frame.height * CGFloat(i)
            imageView.frame = CGRect(x: 0, y: yPosition, width: self.view.frame.width, height: self.view.frame.height)
            mainScrollView.contentSize.height = mainScrollView.frame.height * CGFloat(i + 1)
            mainScrollView.addSubview(imageView)
        }
    }
}

最佳答案

您的问题是:

let yPosition = self.view.frame.height * CGFloat(i)


尝试使yPosition:

let yPosition = previousImage.frame.origin.y+previousImage.frame.size.height


只需跟踪上一张图片,然后再移动到下一张图片即可。还将imageView的高度设置为图像的高度,而不是视图的高度。

您可能需要将for循环更改为此:

 var yPosition = 0

for i in 0..<imageArray.count
{
    let imageView = UIImageView()
    imageView.image = imageArray[i]
    imageView.contentMode = .scaleAspectFit

    imageView.frame = CGRect(x: 0, y: yPosition, width: self.view.frame.width, height: self.view.frame.height)
    mainScrollView.addSubview(imageView)

    yPosition += imageView.image?.size.height
    mainScrollView.contentSize.height = yPosition
}

10-08 05:31