Working on Animations Shaking View

Dheeraj Kumar Gunti

Reading Time : ( words)


By Creating effects or some visual transitions to the UIControls in the applications brings more richness to the application. If for example if I am having a UITextField in my View and if I click on any button with out entering text in that UITextField, TextField should behave in such a way that it should say nothing has entered in an effective way. Effective way of representation comes with Animations.

Here is the small sample with shakes the view if nothing entered.

In the below sample I have added UITextField and UIButton. On UIButton TouchUpInside event I am trying to animate my view.

UIKit and CoreAnimation will support animations in iOS application. UIView supports basic animations. In the below example UIView class has AnimateAsync delegate method which performs animation by specifying certain properties like, from where to where the view should animate and for how much duration that a view should animate.

using System;
using UIKit;
using CoreGraphics;
using CoreAnimation;
using Foundation;
using System.Threading.Tasks;
public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    this.Title = "Shake Animation";
    this.View.BackgroundColor = UIColor.White;
    var textField = new UITextField (new CGRect (20, 100, 280, 40));
    textField.BackgroundColor = UIColor.Black;
    textField.TextColor = UIColor.White;
    var clickBtn = new UIButton (UIButtonType.Custom);
    clickBtn.SetTitle ("Click Me", UIControlState.Normal);
    clickBtn.SetTitleColor (UIColor.Black, UIControlState.Normal);
    clickBtn.Font = UIFont.SystemFontOfSize (14f);
    clickBtn.Frame = new CGRect (20, 160, 280, 40);
    clickBtn.TouchUpInside += async (sender, e) => {
        await AnimateShakeAsync (textField);
    };
    this.View.AddSubview (clickBtn);
    this.View.AddSubview (textField);
}
public static async Task AnimateShakeAsync (UITextField view)
{
    await AnimateHorizontalMovementAsync (view, -10);
    await AnimateHorizontalMovementAsync (view, 20);
    await AnimateHorizontalMovementAsync (view, -20);
    await AnimateHorizontalMovementAsync (view, 20);
    await AnimateHorizontalMovementAsync (view, -15);
    await AnimateHorizontalMovementAsync (view, 10);
    await AnimateHorizontalMovementAsync (view, -5);
}
private static async Task AnimateHorizontalMovementAsync (UITextField view, float horizontalOffset)
{
    await UIView.AnimateAsync (0.065, () => view.Frame =
    new CGRect (new CGPoint (view.Frame.Left + horizontalOffset, view.Frame.Top),
    view.Frame.Size));
}

All the methods above can be changed according to the need.

Enjoy Coding..... :)