Tuesday 21 January 2014

Customising or adding subviews to UIAlertView in iOS 7

Hi All, hope everybody is doing good. Today I am planning to discuss about customising alert views in iOS 7. In earlier versions of iOS, we can subclass UIAlertView and add subviews to it by passing addSubview: message. But, in iOS 7 we can't add a sub view to UIAlertView by passing addSubview: message. Even if send message addSubview: message to UIAlertView, there wont be any effect.

I explored different ways to add subviews to UIAlertView in iOS 7 and finally came up with a solution. I have created a single view application and created a subclass of UIAlertView MLKLoadingAlertView.

Added a custom init method as shown below :

Header File :


@interface MLKLoadingAlertView : UIAlertView

- (id)initWithTitle:(NSString *)title;

@end

init method in Implementation File :

- (id)initWithTitle:(NSString *)title
{
    if ( self = [super init] )
    {
        self.title = title;
        self.message = @"\n\n";
        
        [self setDelegate:self];
    }
    
    return self;
}

If you observer initWithTitle method, I have made UIAlertView subclass itself as delegate of UIAlertView. I have implemented following delegate method of UIAlertViewDelegate in MLKLoadingAlertView :


// You can Customise this based on your requirement by adding subviews.
- (void)didPresentAlertView:(UIAlertView *)alertView
{
    NSArray *subviews = [UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController.view.subviews;
    
    if( subviews.count > 1 )
    {
        // iOS while presenting an alertview uses a presening view controller. That controller's view has several subviews. I have picked one
        // subview from it which has frame similar to the alertview frame.
        UIView *presentedView = [subviews objectAtIndex:1];
        
         UIActivityIndicatorView *customActivityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [customActivityIndicator startAnimating];
        customActivityIndicator.center = ACTIVITY_INDICATOR_CENTER;
        
        [presentedView addSubview:customActivityIndicator];
    }
}

What I did is, when alert view is presented, I am trying to access alert view via subviews of presentedViewController's view in following way :

[UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController.view.subviews

After getting access to UIAlertView instance, I am adding subviews to it.





I have created an example to demonstrate this and placed code in github. You can download source code form Here

Hope this tutorial helps who ever looking for customising UIAlertView in iOS 7 by adding subviews.

Please feel free to add your comments.

No comments:

Post a Comment