0

例如,当用户触摸按钮时,我希望能够创建元素(如 UIViews)

NSMutableString *myVar = [NSMutableString stringWithFormat:@"_view%i", num];
UIView * newView = [self valueForKey:myVar];

但没有添加所有

UIView * _view1;
UIView * _view2;
...

在 .h 文件中(如果可能的话..)

4

4 回答 4

1

您可以使用 NSMutableArray 来保存它们。每次创建新视图时,只需将其添加到数组中。

于 2013-07-24T14:22:06.480 回答
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
于 2013-07-24T14:53:43.337 回答
0

这是保罗答案的代码实现:

- (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];
    }
}
于 2013-07-24T14:46:50.243 回答
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];
}
于 2013-07-24T15:13:01.747 回答