我有一个包含5个项目的数组。此数组是动态的,因此项目数可能会有所不同。
我有UIVIewController
,如下图所示。在我的UIView
中,有很少的组件(如按钮等)。根据上面数组中的项目数量,我想将UIVIew
添加到我的UIViewContorller
,如图所示。
例如:数组中有5个项目,然后我需要将UIView
添加到我的UIViewController
。
1。)我不想为UIView使用XIB
文件,但只想使用StoryBoard
。如何设计UIView
中的StoryBoard
?
2.。)如果数组中的项目数量增加,我如何动态地将UIView
添加到UIViewController
?
答案 0 :(得分:1)
遍历你的数组(我假设你的数组包含UIViews,如果没有,你可以相应更新),如:
for(UIView *subView in arrayOfItems){
subView.position = specify the position
[self.view addSubview:subView];
}
答案 1 :(得分:0)
1)你需要创建一个类,properties
有IBOutlets
,如下所示:
@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。