Iphone 以编程方式创建新的UI元素
例如,当用户触摸按钮时,我希望能够创建元素(如UIView)Iphone 以编程方式创建新的UI元素,iphone,objective-c,user-interface,Iphone,Objective C,User Interface,例如,当用户触摸按钮时,我希望能够创建元素(如UIView) NSMutableString *myVar = [NSMutableString stringWithFormat:@"_view%i", num]; UIView * newView = [self valueForKey:myVar]; 但是没有添加所有 UIView * _view1; UIView * _view2; ... 在.h文件中(如果可能的话…)可以使用NSMutableArray保存它们。每次创建新视图时,只
NSMutableString *myVar = [NSMutableString stringWithFormat:@"_view%i", num];
UIView * newView = [self valueForKey:myVar];
但是没有添加所有
UIView * _view1;
UIView * _view2;
...
在.h文件中(如果可能的话…)可以使用NSMutableArray保存它们。每次创建新视图时,只需将其添加到数组中。以下是pauls answer的代码实现:
- (IBAction)userTouchedButton:(id)sender{
for (int i = 0; i < 100; i++) {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
[view setBackgroundColor:[UIColor redColor]];//to distinguish theseViews from other views
[view setTag:i];//to identified it later
[_array insertObject:view atIndex:i];// globleMutble array
[self.view addSubview:view];
}
}
-(iAction)用户触摸按钮:(id)发送者{
对于(int i=0;i<100;i++){
UIView*view=[[UIView alloc]initWithFrame:CGRectMake(x,y,width,height)];
[view setBackgroundColor:[UIColor redColor]];//将这些视图与其他视图区分开来
[查看setTag:i];//稍后将其标识
[\u array insertObject:view atIndex:i];//globlemutable数组
[self.view addSubview:view];
}
}
以下是示例代码,它可以实现您想要的功能
@interface MyViewController ()
@property (strong, nonatomic) NSMutableArray *listChildViews;
@end
@implementation MyViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.listChildViews = [[NSMutableArray alloc] init];
}
- (IBAction)addChildViewTapped:(id)sender
{
int numChildViews = [self.listChildViews count];
++numChildViews;
// add new child view
NSString *labelForNewView = [NSString stringWithFormat:@"view %d", numChildViews];
CGFloat labelHeight = 28.0;
UILabel *childView = [[UILabel alloc] initWithFrame:CGRectMake(10, numChildViews*labelHeight, 120.0, labelHeight)];
childView.text = labelForNewView;
[self.listChildViews addObject:childView];
[self.view addSubview:childView];
}
@end
您无需在
.h
文件中添加视图。只需在添加它们之前和添加它们的位置进行实例化
-(void) addButton
{
UIView *view = [self view];
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 setTitle:@"My Button" forState:UIControlStateNormal];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 0, 0)];
[myLabel setText:@"My Label"];
[button1 sizeToFit];
[myLabel sizeToFit];
[view addSubview:button1];
[view addSubview:myLabel];
}
使用FOR-LOOP也可以这样做。我不确定是否可以在.h文件中创建它,但可以像fa7d0所说的那样在.m文件中使用FOR-LOOP。但最后,我希望视图具有“名称”(_-view1,_-view2,…)