代码中有注释,就直接上代码了
import Foundationimport UIKitextension 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. }}
效果图
回调函数打印
以上是内存溢出为你收集整理的Swift带振动效果的UITextField全部内容,希望文章能够帮你解决Swift带振动效果的UITextField所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)