John John - 6 months ago 42
iOS Question

Progress animated UIButton

I was wondering to to achieve this loading

UIButton
that behaves like a progress bar. When the progress reaches 100% it activates (
button.enabled = true
) the button.. I learned how to do two state button using images and also transitional based animation for button like material design
UIButton
ripple effect but I can't figure out how to achieve this.

This is the screenshot of an app that have this kind of button behaviour:

loading progress at the "Resend Activation Code" button

Answer

Here you go, I hacked up an example for you in case you don't understand what I mean:

ProgressButton.h

#import <UIKit/UIKit.h>

@interface ProgressButton : UIView

@property (nonatomic, strong) UIView *fillBar;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIButton *button;

@property (nonatomic, strong) NSLayoutConstraint *fillWidthConstraint;

-(void)setFillPercentage:(CGFloat)decimalPercentage Animated:(BOOL)animated;

@end

ProgressButton.m

#import "ProgressButton.h"

@implementation ProgressButton

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if(self)
    {
        [self initViews];
        [self initConstraints];
    }

    return self;
}

-(void)initViews
{
    self.layer.cornerRadius = 5.0;
    self.clipsToBounds = YES;
    self.backgroundColor = [UIColor lightGrayColor];


    _fillBar = [[UIView alloc] init];
    _fillBar.backgroundColor = [UIColor colorWithRed:47.0/255.0 green:204.0/255.0 blue:112.0/255.0 alpha:1.0];

    _label = [[UILabel alloc] init];
    _label.text = @"Resend Activation Code";
    _label.textColor = [UIColor whiteColor];
    _label.textAlignment = NSTextAlignmentCenter;

    _button = [[UIButton alloc] init];
    _button.userInteractionEnabled = NO;

    [self addSubview:_fillBar];
    [self addSubview:_label];
    [self addSubview:_button];
}

-(void)initConstraints
{
    _fillBar.translatesAutoresizingMaskIntoConstraints = NO;
    _label.translatesAutoresizingMaskIntoConstraints = NO;
    _button.translatesAutoresizingMaskIntoConstraints = NO;

    id views = @{
                 @"fillBar": _fillBar,
                 @"label": _label,
                 @"button": _button
                 };

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label]|" options:0 metrics:nil views:views]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label]|" options:0 metrics:nil views:views]];

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[button]|" options:0 metrics:nil views:views]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[button]|" options:0 metrics:nil views:views]];

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[fillBar]" options:0 metrics:nil views:views]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[fillBar]|" options:0 metrics:nil views:views]];

    _fillWidthConstraint = [NSLayoutConstraint constraintWithItem:_fillBar attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:0.0];

    [self addConstraint:_fillWidthConstraint];
}

-(void)setFillPercentage:(CGFloat)decimalPercentage Animated:(BOOL)animated
{
    NSTimeInterval duration = 0.0;

    if(animated)
    {
        duration = 0.5;
    }

    self.fillWidthConstraint.constant = self.bounds.size.width * decimalPercentage;

    [UIView animateWithDuration:duration animations:^{
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.button.userInteractionEnabled = self.fillWidthConstraint.constant >= self.bounds.size.width ? YES : NO;
    }];
}

@end

How To Use

In your view controller, create a property for this progressButton:

#import <UIKit/UIKit.h>
#import "ProgressButton.h"

@interface ViewController : UIViewController

@property (nonatomic, strong) ProgressButton *progressButton;

@end

Then in your ViewController.m file, you can attach a selector to the button touch up event in the initialisation code:

self.progressButton = [[ProgressButton alloc] init];
[self.progressButton.button addTarget:self action:@selector(buttonTapped) forControlEvents:UIControlEventTouchUpInside];

When you're ready to set the button's progress, pass in a decimal percentage in the range 0.0 to 1.0 where 1.0 represents 100%:

[self.progressButton setFillPercentage:0.5 Animated:YES];

Here's the complete ViewController.m file:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self initViews];
    [self initConstraints];


    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.progressButton setFillPercentage:0.5 Animated:YES];
    });



    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.progressButton setFillPercentage:1.0 Animated:YES];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initViews
{
    self.progressButton = [[ProgressButton alloc] init];
    [self.progressButton.button addTarget:self action:@selector(buttonTapped) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:self.progressButton];
}

-(void)initConstraints
{
    self.progressButton.translatesAutoresizingMaskIntoConstraints = NO;

    id views = @{
                 @"progressButton": self.progressButton
                 };

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[progressButton]-20-|" options:0 metrics:nil views:views]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.progressButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
}

-(void)buttonTapped
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Resend Action Code?" message:@"Are you sure?" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        NSLog(@"resend activation placeholder code");

    }];

    UIAlertAction *actionNo = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDefault handler:nil];

    [alertController addAction:actionYes];
    [alertController addAction:actionNo];

    [self presentViewController:alertController animated:YES completion:nil];
}

@end

You end up with something like this if you use my ViewController example:

screenshot 1 screenshot 2

The button shouldn't be clickable if the progress button progress isn't 100%.

Comments