代码中有注释,就直接上代码了
import Foundation
import UIKit
extension UITextField{
//定义类型
enum ShakeType {
case Horizontal
case Vertical
}
/**
UITextField的振动方法
- parameter time: 振动次数
- parameter delta: 振动偏移量
- parameter speed: 动画速度
- parameter shakeType: 振动类型
- parameter completion:
*/
func shakeTextField(time: Int = 10,delta: CGFloat = 5,speed: NSTimeInterval = 0.03,shakeType: ShakeType = .Horizontal,completion:(() -> Void)? = nil){ //根据time的奇偶来确定振动方向 let direction:CGFloat = (time % 2 == 0) ? 1 : -1 UIView.animateWithDuration(speed,animations: { //根据振动类型选择动画 self.transform = (shakeType == ShakeType.Horizontal) ? CGAffineTransformMakeTranslation(delta * direction,0) : CGAffineTransformMakeTranslation(0,delta * direction) }) { (finished) in if time <= 0{ UIView.animateWithDuration(speed,animations: { self.transform = CGAffineTransformIdentity },completion: { (finished) in //如果有回调方法,则实现回调方法 if let comp = completion{ comp() } }) return } self.shakeTextField(time - 1,delta: delta,speed: speed,shakeType: shakeType,completion: completion) } } }
函数调用
class ViewController: UIViewController {
var textField:UITextField!
var textField1:UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
textField = UITextField(frame: CGRect(x: 10,y: 100,width: 200,height: 40))
textField.backgroundColor = UIColor.grayColor()
self.view.addSubview(textField)
textField1 = UITextField(frame: CGRect(x: 10,y: 150,height: 40))
textField1.backgroundColor = UIColor.grayColor()
self.view.addSubview(textField1)
let btn = UIButton(frame: CGRect(x: 10,y: 200,height: 40))
btn.backgroundColor = UIColor.blueColor()
btn.setTitle("振动吧",forState: .normal)
btn.addTarget(self,action: #selector(self.startShake),forControlEvents: .TouchUpInside)
self.view.addSubview(btn)
}
func startShake(){
textField.shakeTextField(shakeType: UITextField.ShakeType.Vertical) {
print("我振动了1")
}
textField1.shakeTextField(shakeType: UITextField.ShakeType.Horizontal) {
print("我振动了2")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// dispose of any resources that can be recreated.
}
}
效果图
回调函数打印