我需要在 UIImageView 中以自动水平幻灯片的形式呈现一系列图像。使用 UIScrollView 和 isPaginationEnabled 属性,我可以手动滚动图像。
这是ViewController.swift的代码-
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
let imageArray: [UIImage] = (1...5).map { UIImage(named: "image\($0)")! }
let scrollView: UIScrollView = {
let scroll = UIScrollView()
scroll.isPagingEnabled = true
scroll.showsVerticalScrollIndicator = false
scroll.showsHorizontalScrollIndicator = false
scroll.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
return scroll
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.scrollView)
setupImages(imageArray)
}
func setupImages(_ images: [UIImage]) {
for i in 0..<images.count {
let imageView = UIImageView()
imageView.image = images[i]
let xPosition = UIScreen.main.bounds.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: scrollView.frame.width, height: scrollView.frame.height)
imageView.contentMode = .scaleAspectFit
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
scrollView.addSubview(imageView)
scrollView.delegate = self
}
}
}
是否可以每隔几秒钟自动滚动图像并使图像保持幻灯片显示?