我有一系列5个安全问题(问题:UILabel
,回答:UITextField
)。
我试图让用户只回答2个问题。
当用户回答2个问题时,我正在尝试禁用UITextField
的其余部分。
我可以将它变成lightGray,但是当用户点击第3 UITextField
时,没有任何事情发生。
另一件事,
我试图将文本保留在UITextField
内,但是当用户向后或向前搜索问题消失时,不知怎的viewDidLoad
总是在它应该只调用一次时被调用。
我试图将NO
设置为UITextFields
enabled
& userInteractionEnabled
属性,但不起作用。
我全班同学,我很乐意帮忙:
#define kUN_CHECKED 0
#define kCHECKED 1
@interface QuestionsAnswersPage () {
NSUserDefaults *defaults;
NSMutableDictionary *_QnA;
}
@end
@implementation QuestionsAnswersPage
- (void)setupGUI
{
NSString *culture = MFLocalizedString(@"culture", nil);
if ([culture isEqualToString:@"he-IL"] || [culture isEqualToString:@"ar-EG"]) {
for (UIView *view in self.contentView.subviews) {
if ([view isKindOfClass:[UILabel class]]) {
[(UILabel *)view setTextAlignment:NSTextAlignmentRight];
}
if ([view isKindOfClass:[UITextField class]]) {
[(UITextField *)view setTextAlignment:NSTextAlignmentRight];
}
if ([view isKindOfClass:[UITextView class]]) {
[(UITextView *)view setTextAlignment:NSTextAlignmentRight];
}
}
}
else {
for (UIView *view in self.view.subviews) {
if ([view isKindOfClass:[UILabel class]]) {
[(UILabel *)view setTextAlignment:NSTextAlignmentLeft];
}
if ([view isKindOfClass:[UITextField class]]) {
[(UITextField *)view setTextAlignment:NSTextAlignmentLeft];
}
if ([view isKindOfClass:[UITextView class]]) {
[(UITextView *)view setTextAlignment:NSTextAlignmentLeft];
}
}
}
}
- (void)setupLayout
{
[self setupIOS7Layout];
[self setupNaviBarWithTitle:MFLocalizedString(@"sequrity_questions", nil)];
}
- (void)setupIOS7Layout
{
self.edgesForExtendedLayout=UIRectEdgeNone;
self.extendedLayoutIncludesOpaqueBars=NO;
self.automaticallyAdjustsScrollViewInsets=NO;
}
- (void)setupNaviBarWithTitle:(NSString *)title
{
[self.navigationController.navigationBar setBarTintColor:OrangeOfficialColor];
[self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
self.navigationItem.title = title;
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:MFLocalizedString(@"continue_text", nil)
style:UIBarButtonItemStylePlain
target:self
action:@selector(btnDone:)];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
defaults = [NSUserDefaults standardUserDefaults];
self.textViewDescription.text = MFLocalizedString(@"sequrity_questions_message", nil);
[self setupLayout];
_QnA = [[NSMutableDictionary alloc] init];
[self.navigationController setNavigationBarHidden:NO animated:YES];
[self performSelectorOnMainThread:@selector(setupGUI) withObject:nil waitUntilDone:YES];
self.imageBG.image = [UIImage imageNamed:@"splash.png"];
if ([UIScreen mainScreen].bounds.size.height == 568) {
self.imageBG.image = [UIImage imageNamed:@"splash-568h.png"];
}
// self.textAnswer1.delegate = self;
// self.textAnswer2.delegate = self;
// self.textAnswer3.delegate = self;
// self.textAnswer4.delegate = self;
// self.textAnswer5.delegate = self;
// self.textAnswer1.keyboardType = UIKeyboardTypeNumberPad;
// self.textAnswer2.keyboardType = UIKeyboardTypeNumberPad;
// self.textAnswer3.keyboardType = UIKeyboardTypeNumberPad;
// self.textAnswer4.keyboardType = UIKeyboardTypeNumberPad;
// self.textAnswer5.keyboardType = UIKeyboardTypeNumberPad;
//
// self.labelQuestion1.lineBreakMode = NSLineBreakByWordWrapping;
// self.labelQuestion2.lineBreakMode = NSLineBreakByWordWrapping;
// self.labelQuestion3.lineBreakMode = NSLineBreakByWordWrapping;
// self.labelQuestion4.lineBreakMode = NSLineBreakByWordWrapping;
// self.labelQuestion5.lineBreakMode = NSLineBreakByWordWrapping;
self.textAnswer1.placeholder = MFLocalizedString(@"answer_only_in_numbers", nil);
self.textAnswer2.placeholder = MFLocalizedString(@"answer_only_in_numbers", nil);
self.textAnswer3.placeholder = MFLocalizedString(@"answer_only_in_numbers", nil);
self.textAnswer4.placeholder = MFLocalizedString(@"answer_only_in_numbers", nil);
self.textAnswer5.placeholder = MFLocalizedString(@"answer_only_in_numbers", nil);
/*
BOOL didGetQuestion = [defaults boolForKey:@"didGetQuestion"];
if (didGetQuestion) {
[self handleQuestions];
}
else {
[defaults setBool:YES forKey:@"didGetQuestion"];
[defaults synchronize];
[SVProgressHUD show];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[appDelegate startParsingGetQuestions];
[SVProgressHUD dismiss];
[self handleQuestions];
});
}
*/
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self saveAskForPasswordState:NO];
BOOL didGetQuestion = [defaults boolForKey:@"didGetQuestion"];
if (didGetQuestion) {
[self handleQuestions];
}
else {
[defaults setBool:YES forKey:@"didGetQuestion"];
[defaults synchronize];
[SVProgressHUD show];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[appDelegate startParsingGetQuestions];
[SVProgressHUD dismiss];
[self handleQuestions];
});
}
}
- (void)handleQuestions
{
self.labelQuestion1.text = [defaults objectForKey:@"question_number_1"];
self.labelQuestion2.text = [defaults objectForKey:@"question_number_2"];
self.labelQuestion3.text = [defaults objectForKey:@"question_number_3"];
self.labelQuestion4.text = [defaults objectForKey:@"question_number_4"];
self.labelQuestion5.text = [defaults objectForKey:@"question_number_5"];
NSString *question1 = [defaults objectForKey:@"user_question_id_1"];
NSString *question2 = [defaults objectForKey:@"user_question_id_2"];
NSString *answer1 = [defaults objectForKey:@"user_answer_id_1"];
NSString *answer2 = [defaults objectForKey:@" user_answer_id_2"];
if (answer1.length == 0 || answer2.length == 0) {
NSLog(@"User didn't fill 2 questions.");
}
else {
for (UIView *view in self.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *field = (UITextField *)view;
if (field.tag == question1.integerValue) {
field.text = answer1;
}
else if (field.tag == question2.integerValue) {
field.text = answer2;
}
else {
field.userInteractionEnabled = NO;
field.enabled = NO;
UILabel *label = (UILabel *)[self.contentView viewWithTag:field.tag+5];
label.textColor = [UIColor lightGrayColor];
}
}
}
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textFieldDidChange:)
name:UITextFieldTextDidChangeNotification
object:nil];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextFieldTextDidChangeNotification
object:nil];
}
- (void)dismissKeyboard
{
[self.textAnswer1 resignFirstResponder];
[self.textAnswer2 resignFirstResponder];
[self.textAnswer3 resignFirstResponder];
[self.textAnswer4 resignFirstResponder];
[self.textAnswer5 resignFirstResponder];
}
- (void)saveAskForPasswordState:(BOOL)isChecked
{
if (isChecked)
{
[defaults setObject:@"true" forKey:@"askForPassword"];
}
else
{
[defaults setObject:@"false" forKey:@"askForPassword"];
}
[defaults synchronize];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (IBAction)btnDone:(id)sender
{
NSUInteger qCounter = 0;
for (UIView *view in self.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *field = (UITextField *)view;
if (field.text.length > 0) {
qCounter++;
[defaults setObject:[NSString stringWithFormat:@"%ld", (long)field.tag]
forKey:[NSString stringWithFormat:@"user_question_id_%lu", (unsigned long)qCounter]];
[defaults setObject:field.text
forKey:[NSString stringWithFormat:@"user_answer_id_%lu", (unsigned long)qCounter]];
[defaults synchronize];
}
}
}
if (qCounter == 2) {
EmergencyPickContacts *controller = [self.storyboard instantiateViewControllerWithIdentifier:
NSStringFromClass([EmergencyPickContacts class])];
[self.navigationController pushViewController:controller animated:YES];
// [self performSegueWithIdentifier:@"QuestionsToEmergencySegue" sender:self];
}
else {
NSLog(@"User didn't fill 2 questions.");
}
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
- (BOOL)willResign
{
NSUInteger counter = 0;
for (UIViewController *view in self.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *field = (UITextField *)view;
if (field.text.length > 0) {
counter++;
}
}
}
return counter == 2;
}
#pragma mark - UITextFieldDelegate Methods
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
NSUInteger counter = 0;
// Count how many questions have answers
for (UIView *view in self.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *field = (UITextField *)view;
if (field.text.length > 0) {
counter++;
}
}
}
if (textField.text.length > 0 && counter == 2) {
for (UIView *view in self.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *field = (UITextField *)view;
if (field.text.length == 0) {
field.userInteractionEnabled = NO;
field.enabled = NO;
[self changeQuestionTextColorWithID:field.tag willBlock:YES];
}
}
}
}
else {
for (UIView *view in self.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *field = (UITextField *)view;
field.userInteractionEnabled = YES;
field.enabled = YES;
[self changeQuestionTextColorWithID:field.tag willBlock:NO];
}
}
}
}
- (void)changeQuestionTextColorWithID:(NSUInteger)answerTag willBlock:(BOOL)block
{
UILabel *label = (UILabel *)[self.contentView viewWithTag:answerTag+5];
label.textColor = block ? [UIColor lightGrayColor] : [UIColor darkGrayColor];
}
- (void)textFieldDidChange:(NSNotification *)notification
{
UITextField *textField = (UITextField *)notification.object;
if (textField.text.length == 0) {
for (UIView *view in self.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *field = (UITextField *)view;
field.userInteractionEnabled = YES;
field.enabled = YES;
UILabel *label = (UILabel *)[self.contentView viewWithTag:field.tag+5];
label.textColor = [UIColor darkGrayColor];
}
}
}
}
- (NSUInteger)numberOfActiveTextFields
{
NSUInteger counter = 0;
for (UIView *view in self.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
if ([(UITextField*)view text].length > 0) {
counter++;
}
}
}
return counter;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0) || [string isEqualToString:@""];
}
@end
答案 0 :(得分:2)
<强>简介强>
Apple提供UITextFieldDelegate协议供您使用。此协议提供了有用的方法,可帮助您获取有关UITextField状态的信息,包括用户是否已开始编辑它们(这可能对您有用)。
实施此协议
在Objective-C中实现UITextFieldDelegate协议需要几个步骤。下面提供了高级概述。这个答案将更详细地介绍以下步骤。
将UITextFieldDelegate添加到您的UIViewController
这一步非常简单。继续打开视图控制器的头文件(.h文件)(例如QuestionsAnswersPage.h)。
您应该看到类似的内容:
@interface QuestionsAnswersPage : UIViewController
// some of your code...
@end
UIViewController
后,添加<UITextFieldDelegate>
。现在它看起来像:
@interface QuestionsAnswersPage : UIViewController <UITextFieldDelegate>
// some of your code...
@end
将UITextFields的委托设置为UIViewController
有两种方法可以做到这一点。第一个是通过故事板,第二个是程序化的。我将为您提供程序化版本。
在实施文件(.m文件)中找到viewDidLoad:
方法(例如QuestionsAnswersPage.m)。在此方法中,添加以下代码行。
yourTextField1.delegate = self;
yourTextField2.delegate = self;
yourTextField3.delegate = self;
// ... similarly for other text fields ...
请记住替换上面代码行中的文本字段名称。
实施适当的方法
此时,您的委托已准备好进行方法实施。这是一种对您特别有用的方法。只需在您的实现(.m文件)中添加此方法,并使用您的实现填充其正文。请记住,您可能需要具有充当计数器或引用的全局变量,以便于您专门尝试执行此操作。
/** This method lets you know that a particular text field has finished edits.
*/
- (void)textFieldDidEndEditing:(UITextField *)textField {
/* It would be a good idea here to check if the following things
* (1) Is the UITextField blank? (check whether it has stuff in it or not)
* (2) If the UITextField is not blank, then have you reached the maximum
* number of filled-in text fields? if so, disable all the empty ones.
* (3) If the UITextField is blank, then you might have to re-enable user
* user interaction with the other UITextFields, if this UITextField was
* filled in before
*/
}
您可能需要的另一个好方法是:
/** This method lets you know that a particular text field is now being edited.
*/
- (void)textFieldDidBeginEditing:(UITextField *)textField {
// Your code here...
}
磨练您的实施
此时你已经全部成立了。我建议使用一个计数器来检查有多少UITextField已经有文本,并提供跟踪这些文本的参考;通过这种方式,您可以轻松跟踪UITextField中的更改。祝您好运,再次,您可以找到有关UITextFieldDelegate here的更多信息。