在我的应用程序中,我想以编程方式在另一个下方添加文本字段,如果需要,单击按钮。我已经提供了两个textFields。如果用户想要添加另一个文本字段,他可以通过单击按钮来完成。我已经编写了代码来获取文本字段,但问题是它与已经设计的textFields重叠。我该怎么办?
有没有办法可以获得已设计文本字段的x和Y坐标,这样我就可以相对于那些坐标放置新的textField。
答案 0 :(得分:0)
使用计数器并像这个计数器* texfield.frame.size.height一样计算y。
答案 1 :(得分:0)
此代码添加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.
}
您可以对此代码进行任何其他更改。 我想这个例子解释了你的答案。
希望它有所帮助。