-1

朋友们

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

4

2 回答 2

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];

}

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

于 2012-04-16T08:40:35.263 回答
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];
}

希望这会帮助你。

于 2012-04-15T02:44:02.597 回答