在 iOS 中以编程方式在另一个文本字段下方添加文本字段

Adding textfield below another textfield programmatically in iOS

在我的应用程序中,如果需要单击按钮,我想以编程方式在另一个文本字段下方添加文本字段。我已经提供了两个文本字段。如果用户想添加另一个文本字段,他可以通过单击按钮来实现。我已经编写了代码来获取文本字段,但问题是它与已经设计的文本字段重叠。我该怎么做?

有什么方法可以让我获得已设计的文本字段的 x 和 Y 坐标,以便我可以相对于这些坐标放置新的文本字段。

使用计数器并像这个计数器*texfield.frame.size.height 一样计算 y。

此代码添加 textField 以在每次单击按钮时动态查看

ExampleViewController.h

#import <UIKit/UIKit.h>

@interface ExampleViewController :UIViewController<UITextFieldDelegate>

@property int positionY;
@property int fieldCount;

@property (strong,nonatomic)  UIScrollView *scroll;

@end

ExampleViewController.m

#import "ExampleViewController.h"

@interface ExampleViewController ()

@end

@implementation ExampleViewController

@synthesize positionY;
@synthesize fieldCount;
@synthesize scroll;

- (void)viewDidLoad {
  [super viewDidLoad];



scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scroll.backgroundColor = [UIColor whiteColor];

[self.view addSubview:scroll];

UIButton *clickToCreateTextField = [[UIButton alloc] initWithFrame:CGRectMake(40, 80, self.view.frame.size.width-80, 75)];
[clickToCreateTextField setTitle:@"Create Text Field" forState:UIControlStateNormal];
[clickToCreateTextField addTarget:self action:@selector(clickedButton) forControlEvents:UIControlEventTouchUpInside];
[clickToCreateTextField setBackgroundColor:[UIColor blackColor]];
[scroll addSubview:clickToCreateTextField];

positionY = clickToCreateTextField.center.y;
fieldCount = 0;


// Do any additional setup after loading the view.
}

-(void) clickedButton{
  //add text field programmitacally
  UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(40, positionY, self.view.frame.size.width-80, 75)];
  textField.delegate = self;
//give a tag to determine the which textField tapped
textField.tag = fieldCount;
textField.placeholder = [NSString stringWithFormat:@"Your dynamically created textField: %d", fieldCount ];
[scroll addSubview:textField];

//check if the textFields bigger than view size set scroll size and offset
if (positionY>= self.view.frame.size.height) {
    scroll.contentOffset = CGPointMake(0, positionY);
    scroll.contentSize = CGSizeMake(scroll.frame.size.width, scroll.frame.size.height+positionY);
}

fieldCount++;
//increase the position with a blank place
positionY = positionY+textField.frame.size.height+20;
}
#pragma mark TextField Delegate Methods
  -(void) textFieldDidBeginEditing:(UITextField *)textField{
//Do what ever you want
}

-(void) textFieldDidEndEditing:(UITextField *)textField{
  [textField resignFirstResponder];
//do anything
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField{
  [textField resignFirstResponder];
  return YES;
}

-(void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}

您可以对此代码进行任何其他更改。 我认为这个例子解释了你的答案。

希望对您有所帮助。