我有一个包含图像数组的 ScrollView ,我想为其设置动画,从右到左更改图像。我的 ScrollView :
@IBOutlet weak var scrollView: UIScrollView!
var imageArray = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.frame = view.frame
imageArray = [UIImage(named:"image3")!,UIImage(named:"image4")!,UIImage(named:"image1")!]
for i in 0..<imageArray.count{
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.image = imageArray[i]
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: self.scrollView.frame.width, height: 205)
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
scrollView.addSubview(imageView)
}
startAnimating()
}
对于动画,我用:
func startAnimating() {
UIView.animateKeyframes(withDuration: 2, delay: 0, options: .repeat, animations: {
self.scrollView.center.x += self.view.bounds.width
}, completion: nil)
}
但是,它是从左向右移动而不是从右向左移动,而且它没有改变图像...我应该怎么做?非常感谢任何指导!谢谢
最佳答案
您正在其父 View 中移动 ScrollView 。 ImageView 是 ScrollView 的 subview (它们在 ScrollView 内),因此它们只是随 ScrollView 一起移动。
要在您的 UIScrollView 中滚动内容,您应该使用它的 contentOffset 属性:
var newOffset = scrollView.contentOffset
newOffset.x += scrollView.frame.size.width
UIView.animate(withDuration: 2, delay: 0, options, .repeat, animations: {
self.scrollView.contentOffset = newOffset
})
另外,您不应该为此使用 animateKeyFrames
。请改用 animate(withDuration:delay:options:animations)
方法。
这里还值得考虑 UIScrollView 是否是正确的选择,这实际上取决于其中要放置多少图像。
如果它总是只有少量图像,那么 ScrollView 是一个不错的选择。
但是,如果要显示更多的图像,那么 UICollectionView 将是更好的选择,因为它会重用其 subview 。
关于ios - 如何在 ScrollView Swift 中为图像变化设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51930643/