我需要动态创建一堆视图。我想知道最好的方法是做什么,因为不需要定义每个视图的坐标,标签和颜色。
我是否需要创建一个多维数组,如果是这样,我该怎么做?
CGRect viewRect1 = { 80.0, 200.0, 160.0, 100.0 };
UIview *myview1 = [[UIview alloc] initWithFrame:viewRect1];
[myview1 setBackgroundColor:[UIColor darkGrayColor]];
答案 0 :(得分:2)
您需要定义一个结构来保存创建UIView
所需的数据。
@interface MyViewDataHolder :NSObject
{
CGRect mViewRect;
UIColor* mDarkGrayColor;
NSInterger mTag;
}
@end
然后创建一个上面的类的对象并在成员中分配值,然后在NSArray
中添加...
<强>编辑:强>
在MyViewDataHolder.h类中
@interface MyViewDataHolder :NSObject
{
CGRect mViewRect;
UIColor* mDarkGrayColor;
NSInteger mTag;
}
@property (nonatomic,assign) CGRect mViewRect;
@property (nonatomic,retain) UIColor* mDarkGrayColor;
@property (nonatomic,assign) NSInteger mTag;
@end
在MyViewDataHolder.mm类中
#import "MyViewDataHolder.h"
@implementation MyViewDataHolder
@synthesize mViewRect,mDarkGrayColor,mTag;
-(void) dealloc
{
[mDarkGrayColor release]
mDarkGrayColor = nil;
}
现在如何使用它....
创建MyViewDataHolder
的对象,如下所示......
MyViewDataHolder* myObj1 = [[MyViewDataHolder alloc] init];
myObj1.mViewRect = CGRectMake(x,y,width,height);
myObj1.tag = 1;
myObj1.mDarkGrayColor = [UIColor redColor];
尽可能多地创建
然后创建NSMutableArray
并将MyViewDataHolder
的每个对象添加到NSMutableArray
。
NSMutableArray* myArray = [[NSMutableArray alloc] init];
[myArray addObject:myObj1];
[myArray addObject:myObj2];
[myArray addObject:myObj3];
and So on ....
当您需要存储的信息时,您可以使用如下...
for(int index =0; index < [myArray count]; index++)
{
MyViewDataHolder* myObj = (MyViewDataHolder*)[myArray objectAtIndex:index];
myView = [[UIView alloc] initWithFrame:myObj.mViewRect];
//incriment x and y to refelect where you want your next view to be suituated
myView.tag = myObj.mTag;
myView.backgroundColor = myObj.mDarkGrayColor;
[self.view addSubview:myView];
[myView release];
}
代码反映了这种方法,虽然我没有编译代码所以使用它作为参考
谢谢,
答案 1 :(得分:0)
你真的不需要将你的视图存储在一个数组中,除非它只是为了方便。
您可以使用for循环创建可变数量的视图:
UIView *myView;
int x=0, y=0;
int viewWidth = 50, viewHeight = 50;
for(int i=0; i<numberOFView; i++){
myView = [[UIView alloc] initWithFrame:CGRectMake(x,y,viewWidth,viewHeight)];
//incriment x and y to refelect where you want your next view to be suituated
myView.tag = i+1;
[self.view addSubview:myView];
[myView release];
}
然后依次访问每个视图并执行一些工作,您可以执行以下操作:
for (UIView *view in self.view.subviews) {
switch (view.tag) {
case 1:
//do something to the view
break;
case 2:
//do something to the view
break;
case 3:
//do something to the view
break;
//and so on...
default:
break;
}
}