Подтвердить что ты не робот

Обнаружение UITextField Lost Focus

Я искал много googling и heree, но ничего полезного.

У меня есть два текстовых поля, и я не могу распознать, какой из них потерял фокус.
Я пробовал все варианты, но ничего.

Здесь textFieldDidEndEditing:

- (void) textFieldDidEndEditing:(UITextField *)textField {  
  NSLog(@"%@", [textField state]);
  NSLog(@"%d", [textField isSelected]);
  NSLog(@"%d", [textField isFirstResponder]);
  NSLog(@"%d", [textField isHighlighted]);
  NSLog(@"%d", [textField isTouchInside]);

  if ( ![textField isFirstResponder] || ![textField isSelected] ) {
  //if ( [textField state] != UIControlStateSelected) {
    NSLog(@"not selected!");
    [...]
    // remove view / etc...
  }
}

Все NSLog возвращает 0! Почему?!?

Как я могу обнаружить потерянный фокус? Этот метод вызывал каждый раз, когда я нажимаю кнопку клавиатуры, не только в конце!
Есть ли альтернативы?

ИЗМЕНИТЬ:
Я не хочу переключаться с текстов, но хочу обнаружить потерянный фокус, когда я нажимаю на экран в любом случае. (клавиатура отклоняется или нет, а каретка отсутствует в текстовом поле)!

спасибо.

4b9b3361

Ответ 1

Чтобы обрабатывать нажатие внешних текстовых полей, вы можете переопределить touchesBegan в своем контроллере вида:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
{
    UITouch *touch = [[event allTouches] anyObject];
    if ([textField1 isFirstResponder] && (textField1 != touch.view))
    {
        // textField1 lost focus
    }

    if ([textField2 isFirstResponder] && (textField2 != touch.view))
    {
        // textField2 lost focus
    }

    ...
}

Ответ 2

 - (BOOL)textFieldShouldReturn:(UITextField *)textField {
      NSLog(@"%d",textFiled.tag);
      NSInteger nextTag = textField.tag + 1;
      UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];   
      if (nextResponder) {
          [nextResponder becomeFirstResponder];
      } else {          
          [textField resignFirstResponder];
      }
      return YES;
  }

UITextField с тегом потерял фокус в методе textFieldShouldReturn

Это поможет вам перейти от одного текстового поля к другому.... просто добавьте тег прираще во всех TextFields ex: 0,1,2,3.... и т.д.

Ответ 3

Это не прямой ответ, так как вы спрашивали о том, как обращаться с потерей фокуса. Я думаю, что бывают случаи, когда нужно иметь явные кнопки сохранения и отмены для отклонения. Особенно в текстовом виде, где вы хотите сохранить ключ возврата для его предполагаемого использования.

Это класс, который добавляет панель инструментов к клавишам "Готово" и "Отмена". У меня это работает в iOS 8 прямо сейчас. Я новичок в iOS, поэтому могут быть лучшие способы сделать это. Всегда открывайте предложения о том, как улучшить.

DismissableTextView.h...

#import <UIKit/UIKit.h>

@interface DismissableTextView : UITextView

@end

DismissableTextView.m...

#import "DismissableTextView.h"

@implementation DismissableTextView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setInputView];
    }
    return self;
}

- (id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setInputView];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setInputView];
}

- (void) setInputView {
    [self createToolbar];
}
-(void) createToolbar {

    // Create toolbar for the keyboard so it can be dismissed...
    UIToolbar* toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    toolbar.barStyle = UIBarStyleDefault;
    toolbar.items = [NSArray arrayWithObjects:
                           [[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClicked)],
                           [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc]initWithTitle:@"Apply" style:UIBarButtonItemStyleDone target:self action:@selector(doneClicked)],
                           nil];
    [toolbar sizeToFit];

    self.inputAccessoryView = toolbar;
}

- (IBAction)didBeginEditDescription:(id)sender
{
}

-(void)cancelClicked{

    // respond to cancel click in the toolbar
    [self resignFirstResponder];
}

-(void)doneClicked{

    // respond to done click in the toolbar
    [self resignFirstResponder];
}

@end

Ответ 4

Когда вы создаете текстовые поля, назначьте им следующие теги:

#define kSomeTag 100
textField.tag = kSomeTag;

В вашем методе textFieldDidEndEditing: (UITextField *) textField в вашем - (void) вы можете указать, какое текстовое поле закончило редактирование, запросив его тег:

if (textField.tag == kSomeTag) {
    // do something
}