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

问题描述:

我希望能够在每次用户点击按钮时在单独的UIViewController中创建新的UI元素(UIProgressView栏)。如何以编程方式创建UI元素

我怎么会去这样做呢?

+3

我不知道你的意思。基于viewController1中的操作,您希望在viewController2出现时显示进度视图?如果是这样,你可以使用viewController2侦听的通知。收到通知时创建进度视图。 – 2012-02-29 02:29:51

+0

完全是这样的...使用通知与使用appDelegate有何不同? – iggy2012 2012-02-29 04:40:59

以编程方式创建一个UIProgressView,它是简单地使用alloc和初始化,设置帧的事情,添加一个子视图,就像这样:

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

} 
+0

非常感谢。 – iggy2012 2012-02-29 03:16:12

+0

没问题。如果你不知道如何编写用户界面,我建议你尽快骨化! – CodaFi 2012-02-29 03:27:31

阅读本指南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];