gpt4 book ai didi

ios - 如何制作 "required"UITextFields?

转载 作者:行者123 更新时间:2023-11-29 00:08:13 25 4
gpt4 key购买 nike

我有一个 ViewController,其中包含我的应用程序用户填写并提交(通过点击 UIButton)的一系列 UITextFields(一种表单)。数据发布到外部数据库 (MySQL),一切都很好。但是,我希望所有 UITextField 都是“必需的”;换句话说,除非所有字段都已填写(包含值),否则“提交”按钮不应发布数据。有谁知道我会怎么做?请参阅下面的代码。

ViewController.h

-(IBAction)addParty:(id)sender;

@property (strong, nonatomic) IBOutlet UITextField *firstname;
@property (strong, nonatomic) IBOutlet UITextField *lastname;
@property (strong, nonatomic) IBOutlet UITextField *guestphone;
@property (strong, nonatomic) IBOutlet UITextField *guestemail;
@property (strong, nonatomic) IBOutlet UITextField *guestsize;

@end

ViewController.m

- (IBAction)addParty:(id)sender
{


NSString *strURL = [NSString stringWithFormat:@"guestfirst=%@&guestlast=%@&guestphone=%@&guestemail=%@&guestsize=%@", firstname.text, lastname.text, guestphone.text, guestemail.text, guestsize.text];
NSLog(@"%@", strURL);


NSData *postData = [strURL dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"postgl.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];


NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

if(conn)
{
NSLog(@"Connection Successful");

[thankyou setHidden:NO];
}
else
{
[thankyou setHidden:YES];
NSLog(@"Connection could not be made");
}

}

最佳答案

一种解决方案是将文本字段的委托(delegate)设置为 UIViewController。

在委托(delegate)方法中实现以下内容

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; 

一旦实现,您应该拥有如下所示的方法:

- (BOOL)enableSubmitButton
{
for (UITextField *textField in @[self.firstname, self.lastname, self.guestphone, self.guestemail, self.guestsize]) {
if (textfield.text.length == 0) {
return NO;
}
}
return YES;
}

然后你应该有一个按钮集的 IBOutlet,你可以在 shouldChangeCharactersInRange 中调用 enableSubmitButton 并将按钮设置为启用,即

@property (nonatomic, weak) IBOutlet UIButton *submitButton;

or could be UIBarButtonItem

@property (nonatomic, weak) IBOutlet UIBarButtonItem *submitButton;

self.submitButton.enabled = [self enableSubmitButton];

关于ios - 如何制作 "required"UITextFields?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26498654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com