xcode 如何以编程方式创建 UI 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9492697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create UI elements programmatically
提问by iggy2012
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.
我希望能够在用户每次点击按钮时在单独的 UIViewController 中创建新的 UI 元素(一个 UIProgressView 栏)。
How would I go about doing this?
我该怎么做呢?
回答by CodaFi
To create a UIProgressView programmatically, it is simply a matter of using alloc and init, setting a frame, and adding a subview, like so:
要以编程方式创建 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];
}
回答by Hanon
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:
大多数 UI 元素都是这样创建的:
UIView *view = [[UIView alloc] initWithFrame:CGRect];
// set the property of the view here
// ...
// finally add your view
[ViewController.view addSubView:view];