在IOS中在运行时添加文本字段

时间:2014-03-13 20:51:36

标签: ios7

我想做一个"添加"按钮在我的滚动视图中添加尽可能多的文本字段。

我已经这样做了

UITextField *text=[[UITextField alloc]initWithFrame:CGRectMake(50,50,200,200)];
[self.scrollView addSubview:text];

但是没有用。

谢谢!

2 个答案:

答案 0 :(得分:0)

如果这是您的完整按钮代码:

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
 [button setTitle:@"Show View" forState:UIControlStateNormal]; 
 button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 

 // add this
 [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
 // continue

 [self.mainScroll addSubview:button];

然后在某处添加:

- (void) buttonPressed:(UIButton *)button {
    UITextField *text=[[UITextField alloc]initWithFrame:CGRectMake(50,50,200,200)];
    text.backgroundColor = [UIColor greenColor]; // just to make sure it's showing up.
    [self.scrollView addSubview:text];
}

答案 1 :(得分:0)

首先创建像这样的通用函数,

-(void)setTextfieldStyle:(UITextField *)pTmpTextField
{
    pTmpTextField.borderStyle = UITextBorderStyleRoundedRect;
    pTmpTextField.font = [UIFont systemFontOfSize:15];
    pTmpTextField.placeholder = @"First Name";
    pTmpTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    pTmpTextField.keyboardType = UIKeyboardTypeDefault;
    pTmpTextField.returnKeyType = UIReturnKeyDone;
    pTmpTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    pTmpTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;    
    pTmpTextField.delegate = self;
}

并使用它来创建UITextFiled,

int y = 0;
for(int i=0;i < 5;i++)
{
UITextField *txtTemp=[[UITextField alloc]initWithFrame:CGRectMake(0, y, 300, 31)];
txtTemp.tag = i;
[self setTextfieldStyle:txtTemp];
[self.view addSubview:txtTemp];
[txtTemp release];
y+=36;
}

这是UITextField的委托方法,

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(@"%@",textField.text);
}

希望这适合你,因为这对我有用。只记住这一点,将文本字段添加到滚动视图中。 在示例中,我将它们添加到我的视图中!