友達
ビューにテキストフィールドを作成するためのボタンとビューからテキストフィールドを削除するための2つのボタンがありますが、すべてのテキストフィールドは異なる2つの位置にあるので、助けてください。私の悪い英語で申し訳ありません。
友達
ビューにテキストフィールドを作成するためのボタンとビューからテキストフィールドを削除するための2つのボタンがありますが、すべてのテキストフィールドは異なる2つの位置にあるので、助けてください。私の悪い英語で申し訳ありません。
ここでは、サンプル コードを提供します。このコードは、ランダムな場所で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];
}
これがあなたを助けることを願っています。
ビュー コントローラーで、テキスト フィールドの配列を設定します。
.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];
}
どの textFields も重複させたくない場合は、ランダムな位置を生成するときにチェックを行う必要があります。