动态地将UIView添加到UIViewController

时间:2015-04-09 10:57:03

标签: ios objective-c iphone uiview uiviewcontroller

我有一个包含5个项目的数组。此数组是动态的,因此项目数可能会有所不同。

我有UIVIewController,如下图所示。在我的UIView中,有很少的组件(如按钮等)。根据上面数组中的项目数量,我想将UIVIew添加到我的UIViewContorller,如图所示。

例如:数组中有5个项目,然后我需要将UIView添加到我的UIViewController

enter image description here

1。)我不想为UIView使用XIB文件,但只想使用StoryBoard。如何设计UIView中的StoryBoard

2.。)如果数组中的项目数量增加,我如何动态地将UIView添加到UIViewController

4 个答案:

答案 0 :(得分:1)

遍历你的数组(我假设你的数组包含UIViews,如果没有,你可以相应更新),如:

for(UIView *subView in arrayOfItems){
       subView.position = specify the position 
       [self.view addSubview:subView];
}

答案 1 :(得分:0)

1)你需要创建一个类,propertiesIBOutlets,如下所示:

@interface MyView ()

@property (weak, nonatomic) IBOutlet UIView *viewContent;

@end

您可以在UIView内设计UIStoryboard并将它们从类连接到ui元素。在之前的xCode版本中,如果您想从UIStoryboard拖到课堂上,则总是会出现问题,必须以不同的方式进行操作。

2)要向UIView添加UIViewController,您只需在subView内添加UIViewController,就像这样:

[self.view addSubView:anyView]

答案 2 :(得分:0)

根据您的设计设置子视图的框架

 for (int i=0;i<YourViewArrayCount; i++) {
            [self.view addSubview:[YourViewArrayCount objectAtIndex:i]];

        }

答案 3 :(得分:0)

在故事板中创建一个UICollectionView,并在其中添加一个带有UIButton的UICollectionViewCell原型,并在UICollectionViewDataSource方法中返回数组计数:

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return yourArray.count;
}

并且为了处理按钮触摸事件,您必须将UIButton标记设置为999,例如在故事板中的UICollectionViewCell原型中,并且在UICollectionViewDataSource方法中,cellForItemAtIndexPath使用其标记获取对该按钮的引用然后以编程方式为其添加触摸事件处理程序:

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"yourCellIdentifier" forIndexPath:indexPath];

    UIButton *button = [cell viewWithTag:999];

    [button addTarget:self action:@selector(buttonTouchHandler:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

最后找出实际触摸的按钮(在哪个indexPath),我建议继承UIButton类并添加NSIndexPath类型的属性(不要忘记将storyboard中的按钮类更改为新的UIButton子类)并在UICollectionViewDataSource方法中使用cellForItemAtIndexPath执行以下操作

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"yourCellIdentifier" forIndexPath:indexPath];

    MySepcialButton *button = [cell viewWithTag:999];

    button.indexPath = indexPath;

    [button addTarget:self action:@selector(buttonTouchHandler:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

这样在buttonTouchHandler:方法中你可以检查按钮属性indexPath。