如何以编程方式创建UI元素

时间:2012-02-29 02:18:29

标签: iphone objective-c ios xcode user-interface

每次用户点击按钮时,我都希望能够在单独的UIViewController中创建新的UI元素(UIProgressView栏)。

我将如何做到这一点?

2 个答案:

答案 0 :(得分:4)

要以编程方式创建UIProgressView,只需使用alloc和init,设置框架以及添加子视图,如下所示:

//.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];

}

答案 1 :(得分:1)

阅读本指南https://developer.apple.com/library/ios/#DOCUMENTATION/WindowsViews/Conceptual/ViewPG_iPhoneOS/CreatingViews/CreatingViews.html

大多数UI元素都是这样创建的:

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

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