使用iphone中的按钮点击在视图上的多个位置创建文本字段

时间:2012-04-14 11:21:54

标签: iphone ios4 iphone-sdk-3.0

朋友

我有两个按钮,一个用于在视图上创建文本字段,另一个用于从视图中删除文本字段,但每个文本字段位于不同的2位置,所以请帮助我谢谢。 抱歉我的英语不好。

2 个答案:

答案 0 :(得分:0)

在这里,我为您提供示例代码。此代码将生成100(//或您可以根据您的要求生成任何文本字段)文本字段与随机位置,您只需单击一下即可删除此文本字段...

UITextField *t[100];//declare it in .h file...

-(void)randomtextfield
{
int n = 100;
int temp;
  for (int i = 0 ; i < 100 ; i++)
  {
    int r = arc4random()%n;
    if(r != temp){
        temp = r;
        CGRect r1 = t[i].frame;      
        t[i].frame = t[temp].frame;
        t[temp].frame = r1; 

        n--;
        [self.view addSubview:t[i]];
     }

 }

}

-(IBAction)addtextfield
{
int x,y;
x=0;
y=0;

for (int i = 0; i<100;i++)
{

    t[i] = [[UITextField alloc]init];
    t[i].frame = CGRectMake(x, y, 100, 30);
    t[i].borderStyle = UITextBorderStyleBezel;

    if(x<320)
    {
        x = x+100;
    }

    else
    {
        x=0;
    }

    if (y<480)
    {
        y= y+30;
    }

    else
    {
        y=0;
    }
  }
  [self randomtextfield];

 }



-(IBAction)removertextfield:(id)sender
{
  NSMutableArray *array = [[NSMutableSet alloc]initWithArray:[self.view subviews]];
   {
    [textfield removeFromSuperview];
   }
 [array release];
}

希望这会对你有所帮助。

答案 1 :(得分:0)

在视图控制器中,为文本字段设置数组 -

.h -

@property (nonatomic, retain) NSMutableArray *myTextFields;

.m -

#define kScreenWidth                480.0 // or set this up elsewhere according to device, etc
#define kScreenHeight               320.0
#define kTextFieldWidth             150.0
#define kTextFieldHeight            36.0

@synthesize myTextFields;

-(id)init {

    self = [super initWithNibName:@"MyViewController" bundle:nil];
    if (self) {
        myTextFields = [[NSMutableArray alloc] init];
    }
    return self;
}


-(IBAction)addTextField {

    CGFloat x = ((CGFloat) rand() / RAND_MAX) * (kScreenWidth - kTextFieldWidth);
    CGFloat y = ((CGFloat) rand() / RAND_MAX) * (kScreenHeight - kTextFieldHeight);

    UITextField *theTextField = [[[UITextField alloc] initWithFrame:CGRectMake(x, y, kTextFieldWidth, kTextFieldHeight)] autorelease];

    theTextField.tag = [myTextFields count] + 1; // so you know which one is being edited

    // set up other text field properties here, like delegate, background, font, etc.

    [self.view addSubview:theTextField];
    [myTextFields addObject:theTextField];

}


-(IBAction)removeTextField {

    if (![myTextFields count]) return;

    UITextField *theTextField = [myTextFields lastObject];

    [theTextField removeFromSuperview];
    [myTextFields removeLastObject];

}

如果您不希望任何textField重叠,则必须在生成随机位置时进行检查。