lorenzoid
lorenzoid

Reputation: 1832

How to create UI elements programmatically

I'd like to be able to create new UI elements (a UIProgressView bar) in a separate UIViewController every time a user taps on a button.

How would I go about doing this?

Upvotes: 2

Views: 8194

Answers (2)

CodaFi
CodaFi

Reputation: 43330

To create a UIProgressView programmatically, it is simply a matter of using alloc and init, setting a frame, and adding a subview, like so:

//.h

#import <UIKit/UIKit.h>

@interface ExampleViewController : UIViewController {

    //create the ivar
    UIProgressView *_progressView;

}
/*I like to back up my iVars with properties.  If you aren't using ARC, use retain instead of strong*/
@property (nonatomic, strong) UIProgressView *progressView;

@end

//.m

@implementation
@synthesize progressView = _progressView;

-(void)viewDidLoad {
    /* it isn't necessary to create the progressView here, after all you could call this code from any method you wanted to and it would still work*/
    //allocate and initialize the progressView with the bar style
    self.progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
    //add the progressView to our main view.
    [self.view addSubview: self.progressView];
    //if you ever want to remove it, call [self.progressView removeFromSuperView];

}

Upvotes: 4

Hanon
Hanon

Reputation: 3927

Read this guide https://developer.apple.com/library/ios/#DOCUMENTATION/WindowsViews/Conceptual/ViewPG_iPhoneOS/CreatingViews/CreatingViews.html

Most of the UI elements create like this:

UIView *view = [[UIView alloc] initWithFrame:CGRect];
//  set the property of the view here
//  ...

//  finally add your view
[ViewController.view addSubView:view];

Upvotes: 1

Related Questions