前几话我们实现了Review按钮的功能,今天来实现Share按钮的功能,由于两个功能的相似性,所以新建一个控制器,ShareViewController类,把ReviewViewController类的代码复制过去进行修改,share中不需要transforView和label,删掉,然后把按钮改成四个放到基view中,代码如下:
let buttonWidth:CGFloat = 60 let buttonY:CGFloat = 200 //三个按钮相同的规格 let faceBtn = UIButton(frame: CGRectMake(100, buttonY, buttonWidth, buttonWidth)) faceBtn.setBackgroundImage(UIImage(named: "facebook"), forState: .Normal) self.view.addSubview(faceBtn) let twitterBtn = UIButton(frame: CGRectMake(160, buttonY, buttonWidth, buttonWidth)) twitterBtn.setBackgroundImage(UIImage(named: "twitter"), forState: .Normal) self.view.addSubview(twitterBtn) let messageBtn = UIButton(frame: CGRectMake(100, 260, buttonWidth, buttonWidth)) messageBtn.setBackgroundImage(UIImage(named: "message"), forState: .Normal) self.view.addSubview(messageBtn) let emailBtn = UIButton(frame: CGRectMake(160, 260, buttonWidth, buttonWidth)) emailBtn.setBackgroundImage(UIImage(named: "email"), forState: .Normal) self.view.addSubview(emailBtn)
然后再DetailViewController中添加share的action
func clickShare(sender: UIButton){ let share = ShareViewController() self.presentViewController(share, animated: true, completion: nil )//临时展示一个控制器 }
运行效果如图:
然后给图片设置一个背景色,颜色的话用mac自带的取色器就可以获得:
现在我们来实现这几个按钮的动画效果,让他们从不同的敌方飞进屏幕然后组合成上图的样子,首先让facebook的图标从下面飞入,让email的图标从上面飞入。
在按钮的代码后面继续增加如下代码:
let upTranslate = CGAffineTransformMakeTranslation(0, -500) let downTranslate = CGAffineTransformMakeTranslation(0, 500) faceBtn.transform = downTranslate emailBtn.transform = upTranslate
标示了这两个按钮的初始位置,因为动画效果要在viewWillApear中实现,所以按钮必须是全局的,所以我们把按钮的声明放在全局中。
var faceBtn: UIButton! var twitterBtn: UIButton! var emailBtn: UIButton! var messageBtn: UIButton!
然后在viewWillAppear中实现动画,如下:
override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.7, options: nil, animations: { let translate = CGAffineTransformMakeTranslation(0, 0) self.faceBtn.transform = translate self.emailBtn.transform = translate }, completion: nil) }
注意一下,我们这次是按钮的飞进,使用的是CGAffineTransformMakeTranslation,依靠坐标来定位,而在Review中使用的方法是整个view从无到有,所以使用的是CGAffineTransforMakeScale。效果如图:
然后如法炮制实现另外两个按钮,延迟设为0.1秒,最后的效果如图,按钮飞入: