【发布时间】:2015-10-06 22:33:44
【问题描述】:
我对 swift/objective C 相当陌生,我想知道是否有人可以帮助我解决与图像视图动画相关的问题(从右到左滚动)。我目前在我的 VC 上有一个 UIImageView,它的动画没有问题。但是,我认为最好使用 UICollectionView 代替。有人可以请我指出正确的方向吗?我还没有深入处理集合视图,所以这个概念对我来说相对较新。我对当前情况的代码是:
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var sponsorAnimation: UIImageView!
let images = [
UIImage(named: "runforcure")!,
UIImage(named: "marquee")!]
var index = 0
let animationDuration: NSTimeInterval = 1
let switchingInterval: NSTimeInterval = 3
override func viewDidLoad() {
super.viewDidLoad()
sponsorAnimation.image = images[index]
animateImageView()
}
func animateImageView() {
CATransaction.begin()
CATransaction.setAnimationDuration(animationDuration)
CATransaction.setCompletionBlock {
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(self.switchingInterval * NSTimeInterval(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
self.animateImageView()
}
}
let transition = CATransition()
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromRight
/*
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromRight
*/
sponsorAnimation.layer.addAnimation(transition, forKey: kCATransition)
sponsorAnimation.image = images[index]
CATransaction.commit()
index = index < images.count - 1 ? index + 1 : 0
}
我的理想情况是一次显示一张图片,并且每 3 秒从右向左滚动一次。
更新:我认为我真的很接近,但是在最后两行代码中我不知道将 self.collectionview 放在哪里? .任何帮助是极大的赞赏。再次提前感谢!
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
let images = [UIImage(named: "oneteam"), UIImage(named: "runforcure")]
var timer = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector("switchImage"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.images.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell
cell.imageView?.image = self.images[indexPath.row]
/*I don't know where to place this line of code? If I place is outside of this function then it says unresolved identifier 'indexPath'*/
self.collectionView?.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Top, animated: true)
return cell
}
}
提前致谢!
【问题讨论】:
-
当前在我的 switchImage() 函数中,indexPath 没有在系统中注册...我肯定错过了什么!
标签: ios animation uiimageview uicollectionview