我希望能够在用户触摸按钮时创建元素(如UIViews)
NSMutableString *myVar = [NSMutableString stringWithFormat:@"_view%i", num];
UIView * newView = [self valueForKey:myVar];
但没有添加所有
UIView * _view1;
UIView * _view2;
...
<。>在.h文件中(如果只有这个可能..)
答案 0 :(得分:1)
您可以使用NSMutableArray来保存它们。每次创建新视图时,只需将其添加到数组中即可。
答案 1 :(得分:1)
以下示例代码可以执行您想要的操作。
@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
答案 2 :(得分:0)
以下是pauls的代码实现答案:
- (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];
}
}
答案 3 :(得分:0)
您无需在.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];
}