您的位置:首页 > 产品设计 > UI/UE

UIKit中ImageView动画堆叠显示的微调整

2016-05-30 18:20 141 查看

大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处.

如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;)



网上看到一个PackingList项目(如果需要源代码可以Q我,或自行在网上搜索下载),用来演示UIKit的各种动画效果,尤其是对自动布局(auto layout)限制产生的动画,运行看一下效果还不错:



如上动画显示,不过,如果你耐心看到最后几个操作,就会发现快速连续点击TableView中的行时会发生图片缩略图发生重叠的现象.

因为代码中每次点击TableView的行就会放大显示对应图片的缩略图,在延时1s后将其移除屏幕.如果你连续点击行的速度小于1s,则就会发生新缩略图和前一个缩略图发生稍许重叠的情况.

虽然本猫不是处女座,但是这细微的瑕疵必须得以清除 ;]

我们来看看如何修改源代码已达到更好的效果.

首先在ViewController.swift中添加2个实例变量:

var imageView:UIImageView!
var isImageViewRemoved = false


第一个用来存放最后一个显示缩略图对应的ImageView,后面一个用来检查是否旧的缩略图已经被删除了.

接着我们微修类中的showItem(_)方法:

@available(iOS 9.0, *)
func showItem(index: Int) {
print("tapped item \(index)")
//add new
if imageView != nil{
imageView.removeFromSuperview()
imageView = nil
isImageViewRemoved = true
}

//let imageView = UIImageView(image: UIImage(named: "summericons_100px_0\(index).png"))
imageView = UIImageView(image: UIImage(named: "summericons_100px_0\(index).png"))
imageView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5)
imageView.layer.cornerRadius = 5.0
imageView.layer.masksToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageView)

let conX = imageView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor)
let conBottom = imageView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor,constant: imageView.frame.height)
let conWidth = imageView.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier: 0.33, constant: -50.0)
let conHeight = imageView.heightAnchor.constraintEqualToAnchor(imageView.widthAnchor)
NSLayoutConstraint.activateConstraints([conX,conBottom,conWidth,conHeight])

view.layoutIfNeeded()

UIView.animateWithDuration(0.8, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: [], animations: {
conBottom.constant = -self.imageView.frame.size.height/2
conWidth.constant = 0.0
self.view.layoutIfNeeded()
}, completion: nil)

UIView.animateWithDuration(0.8, delay: 1.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: [], animations: {
conBottom.constant = self.imageView.frame.size.height
conWidth.constant = -50.0
self.view.layoutIfNeeded()
}){_ in
if !self.isImageViewRemoved{
self.imageView.removeFromSuperview()
self.imageView = nil
}

}
}


我们首先在方法开头添加了旧缩略图是否显示的判断,如果是则将其删除,并将isImageViewRemoved设置为true,这是为了在后面动画的completion中不会出错!

然后我们将动画闭包内的imageView相关的变量开头都加上self,这是为了满足挑剔的编译器.

最后修改最后一个动画的completion,在其中添加如上代码:

if !self.isImageViewRemoved{
self.imageView.removeFromSuperview()
self.imageView = nil
}


编译运行App,现在效果如下:



现在赶脚好多了 ;]

注意上述演示是在竖屏状态下运行的,因为App使用了auto layout,所以无论是横屏还是竖屏,无论是iPhone4s还是iPad pro效果都是一样的.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: