有没有办法结合页面控件在滚动视图中自动布局图像?

Is there a way to auto layout an image in a scroll view combined with page control?

这是我的第一篇文章。我是来自德国的应用程序设计新手,但我仍然希望您能理解我的问题。我用了 Xcode 11 和 Swift 5.

我正在使用页面控件和滚动视图在一个屏幕中的图像之间切换。在iPhone 11 上看起来不错,但是在iPhone 8 上图片的宽度和高度太大,这就是为什么当页面控件位于第二段。第二张图片和第三段也是如此。This hopefully shows the problem. 有没有办法让图片适合屏幕尺寸?

这是我的代码:

```
import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var pageControl: UIPageControl!

    var Pages: [String] = ["Page1","Page2","Page3"]
    var frame = CGRect.zero


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        pageControl.numberOfPages = Pages.count //
        setupScreens()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
    }

    func setupScreens() {
        for index in 0..<Pages.count {
            // 1.
            frame.origin.x = scrollView.frame.size.width * CGFloat(index)
            frame.size = scrollView.frame.size

            // 2.
            let imageView = UIImageView(frame: frame)
            imageView.image = UIImage(named: Pages[index])
            self.scrollView.addSubview(imageView)        }

        // 3.
        scrollView.contentSize = CGSize(width: (scrollView.frame.size.width * CGFloat(Pages.count)), height: scrollView.frame.size.height)
        scrollView.delegate = self


    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
        pageControl.currentPage = Int(pageNumber)
    }

}

```

除了在 viewDidLoad().

中调用 setupScreens() 方法外,您的代码完全可以正常工作

viewDidLayoutSubviews 中调用该方法,以便它获得 scrollView 的正确帧。

override func viewDidLayoutSubviews() {
          setupScreens()
}

here

下载演示