0

Я использую iOS8.0, и я хочу установить UITextFieldDelegate в UITextField внутри элемента управления UISearchBar. Я уже получил текстовое поле внутри панели поиска, и я также могу установить для него собственный текст. Но когда я устанавливаю UITextFieldDelegate на этот TextField, приложение падает каждый раз, когда я касаюсь панели поиска.`unrecognized selector` ошибка при установке делегата в текстовое поле UISearchBar

Пожалуйста, помогите мне взглянуть и сказать, допустим ли я ошибку. Благодарю. Вот аварии Log:

Нагрузочного приложение из-за неперехваченное исключением 'NSInvalidArgumentException', причину: '- [LoginToSafraViewController _searchController]: непризнанный селектор направил к экземпляру 0x7b469440' *** Первого стека бросить вызов: (0 CoreFoundation 0x00962746 exceptionPreprocess + 1 182 libobjc.A.dylib
0x005eba97 objc_exception_throw + 44 2 CoreFoundation
0x0096a705 - [NSObject (NSObject) doesNotRecognizeSelector:] + 277 3
CoreFoundation 0x008b1287 ___forwarding_
+ +1047 4 CoreFoundation 0x008b0e4e _CF_forwarding_prep_0 + 14 5 UIKit 0x012b0e2b - [UISearchBarTextField canBecomeFirstResponder] + 96 6
UIKit 0x010fabac - [UIResponder (внутренний) _canBecomeFirstResponder] + 33 7 UIKit 0x010f923a - [UIResponder becomeFirstResponder] + 240 8 UIKit
0x00fb8348 - [UIView (Иерархия) becomeFirstResponder] + 114 9 UIKit 0x017763e7 - [UITextField becomeFirstResponder] + 51 10 UIKit
0x0137f7f8 - [UITextInteractionAssistant (UITextInteractionAssistant_Internal) setFirstResponderIfNecessary] + 200 11 UIKit
0x01381e26 - [UITextInteractionAssistant (UITextInteractionAssistant_Internal) oneFingerTap:] + 2762 12 UIKit
0x01375677 _UIGestureRecognizerSendActions + 327 13 UIKit
0x01373ef4 - [UIGestureRecognizer _updateGestureWithEvent: buttonEvent:] + 561 14 UIKit 0x01375f3d - [UIGestureRecognizer _delayedUpdateGesture] + 60 15 UIKit 0x013798ba ___UIGestureRecognizerUpdate_block_invoke661 + 57 16 UIKit 0x0137977d

код, чтобы найти текстовое поле:

UITextField *searchTextField = [self findTextFieldInsideSearchBar:x]; 
if (searchTextField != nil) 
{ 
    [arr addObject:searchTextField]; 
    [searchTextField setText:@"sfsfsdf"]; 
    [searchTextField setDelegate:self]; 
} 


-(UITextField*) findTextFieldInsideSearchBar:(UISearchBar*)searchBar 
{ 
    for (UIView* view in searchBar.subviews) { 
     if([[UIDevice currentDevice] systemVersion].floatValue >= 7){ 
      //at iOS v7.0 and later, 
      for (UIView* subSubView in view.subviews) { 
       if([subSubView isKindOfClass:[UITextField class]]) 

        return (UITextField*) subSubView; 
      } 
     }else{ 
      //iOS v6.0 and erlier. 
      if([view isKindOfClass:[UITextField class]]) 
       return (UITextField*) view; 
     } 
    } 
    return nil; 
} 
+3

Ваша ошибка заключается в том, что вы входите в частные внутренние операции 'UISearchBar' и меняете« делегат »частного текстового поля на то, чего он не ожидал. Почему вы пытаетесь изменить свойство 'delegate' текстового поля? – rmaddy

+0

похоже, что вы назначаете UITextFieldDelegate для UITextField, объявили ли вы, что UITextField реализовал протокол UITextFieldDelegate? – Wingzero

+0

Ах! да! Я мой VC, есть много элементов управления UITextField, а также UISearchBar. Я хочу нажимать просмотр, всякий раз, когда клавиатура показывает и скрывает фокусировку текстового поля. Sothat, я реализую UITextFieldDelegate и меняю рамку Self.View, когда это необходимо. Он отлично работает с UITextField, но сбой с UISearchBar. –

ответ

0

Вы не можете установить делегат этого текстового поля напрямую;

Вы должны наследовать свой поискBar и установить делегат текстового поля следующим образом;

MySearchBar* mySearchBar = [[MySearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)]; 
mySearchBar.textFieldDelegate = self; // TO BE NOTED. SETTING textFieldDelegate. SAME WOULD WORK FOR XIB OR STORYBOARD 
[self.view addSubview:mySearchBar]; 

========================

// MySearchBar.h 

#import <UIKit/UIKit.h> 

@interface MySearchBar : UISearchBar 

@property (nonatomic, weak) id<UITextFieldDelegate> textFieldDelegate; 

@end 

============ ===

// MySearchBar.m 

#import "MySearchBar.h" 

@implementation MySearchBar 

/* 
// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect { 
    // Drawing code 
} 
*/ 

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { 

    if (self.textFieldDelegate && [self.textFieldDelegate respondsToSelector:@selector(textFieldShouldBeginEditing:)]) 
    { 
     return [self.textFieldDelegate textFieldShouldBeginEditing:textField];; 
    } 
    else 
    { 
     return true; 
    } 
} //F.E. 

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    if (self.textFieldDelegate && [self.textFieldDelegate respondsToSelector:@selector(textFieldDidBeginEditing:)]) 
    { 
     [self.textFieldDelegate textFieldDidBeginEditing:textField];; 
    } 
}//F.E. 

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField 
{ 
    if (self.textFieldDelegate && [self.textFieldDelegate respondsToSelector:@selector(textFieldShouldEndEditing:)]) 
    { 
     return [self.textFieldDelegate textFieldShouldEndEditing:textField];; 
    } 
    else 
    { 
     return true; 
    } 
} //F.E. 

- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
    if (self.textFieldDelegate && [self.textFieldDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) 
    { 
     [self.textFieldDelegate textFieldDidEndEditing:textField];; 
    } 
} //F.E. 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    if (self.textFieldDelegate && [self.textFieldDelegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) 
    { 
     return [self.textFieldDelegate textField:textField shouldChangeCharactersInRange:range replacementString:string];; 
    } 
    else 
    { 
     return true; 
    } 
} //F.E. 

- (BOOL)textFieldShouldClear:(UITextField *)textField 
{ 
    if (self.textFieldDelegate && [self.textFieldDelegate respondsToSelector:@selector(textFieldShouldClear:)]) 
    { 
     return [self.textFieldDelegate textFieldShouldClear:textField];; 
    } 
    else 
    { 
     return true; 
    } 
} //F.E. 

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
    if (self.textFieldDelegate && [self.textFieldDelegate respondsToSelector:@selector(textFieldShouldReturn:)]) 
    { 
     return [self.textFieldDelegate textFieldShouldReturn:textField];; 
    } 
    else 
    { 
     return true; 
    } 
} //F.E. 

@end 
Смежные вопросы