iOS 맞 춤 형 UISearchBar 내 비게 이 션 표시 줄 iOS 11 동기 화 방법

시스템 네 이 티 브 UISearchBar 는 iOS 11 에서 변 화 를 겪 었 습 니 다.높이 는 원래 의 44 에서 56 으로 바 뀌 었 습 니 다.(기본 높이 로 추정 되 는 것 은 모두 구덩이 에 빠 졌 습 니 다)스타일 도 약간 변화 가 생 겼 습 니 다.예 를 들 어 입력 되 지 않 은 상태 에서 원 각 변화 가 생 겼 습 니 다.확대경 아이콘 과 텍스트 의 문 자 는 가운데 가 아니 라 왼쪽 입 니 다.구체 적 으로 그림 을 보다.

일부 주류 앱 도 네 비게 이 션 표시 줄 에 searchBar 를 삽입 하 는 경우 가 많다.왕 이 클 라 우 드 음악 과 아 는 것 을 예 로 들 면 왼쪽 은 홈 페이지 이 고 오른쪽 은 검색 페이지(커서 주의)이다.

사고 와 사례 를 실현 하 다.
핵심 사상 은 네 비게 이 션 표시 줄 의 title View 와 좌우 의 barButton Item 을 설정 하 는 것 이다.주로 세 가지 방식 이 있어 요.
  •  첫 페이지 내 비게 이 션 표시 줄 의 title View 는 button 을 사용 하여 이 루어 집 니 다.검색 페이지 는 searchBar 를 사용 합 니 다
  • 4.567917.첫 페이지 와 검색 페이지 내 비게 이 션 표시 줄 의 title View 는 모두 searchBar,searchBar 의 스타일 로 두 페이지 에 대해 서로 다른 수정 을 한다.이런 방식 은 우리 가 맞 춤 형 검색 바 를 다시 사용 하여 번 거 로 움 을 줄 일 수 있다
  • 첫 페이지 내 비게 이 션 표시 줄 title View 는 button 을 사용 하여 이 루어 지고 검색 페이지 는 textField 를 사용 합 니 다.이런 방식 은 더욱 철저 하고 유연 하 며 상대 적 으로 복잡 하 다
  • 왜 위 에 있 는 title View 가 button 이 라 고 하 는 거 야?다른 거 아니 야?다른 것 도 물론 이 루어 질 수 있다.button 자체 적 으로 imageView 와 title Label 을 가지 고 있 습 니 다.오프셋 만 설정 하면 우리 가 원 하 는 것 에 쉽게 도달 할 수 있 고 보기 의 등급 이 적 으 며 유창 성에 있어 서 더욱 보장 합 니 다.
    케이스


    왕 이 클 라 우 드 음악 홈 페이지 와 검색 페이지 의 네 비게 이 션 바 보기 등급,title View 는 모두 MCSearchBar 를 사용 하여 이 루어 지고 네 비게 이 션 바 좌우 양쪽 단 추 를 설정 합 니 다.이것 은 앞에서 말 한 두 번 째 사고 와 유사 하 다.
     

    그림 에서 알 수 있 듯 이 첫 페이지 의 네 비게 이 션 표시 줄 은 2 개의 button 으로 구성 되 어 있 고 검색 페이지 는 textField 를 사 용 했 습 니 다.이것 은 앞에서 언급 한 세 번 째 사고 와 유사 합 니 다.
    실전
    사용자 정의 SearchBar 를 통 해 다음 스타일 의 네 비게 이 션 표시 줄 을 실현 합 니 다.

    먼저 UISearchBar 의 초기 화 방법 을 사용자 정의 하고 홈 페이지 와 검색 페이지 의 공통점 과 차이 점 을 살 펴 보 세 요.searchField 의 크기 배경 색 과 일치 합 니 다.이 부분 은 직접 지정 할 수 있 고 placeholder 는 다 르 기 때문에 호출 할 때 제공 해 야 합 니 다.이 를 통 해 OHSearchBar 클래스 를 새로 만 들 고 초기 화 방법 을 만 듭 니 다.
    
    - (instancetype)initWithFrame:(CGRect)frame placeholder:(NSString *)placeholder textFieldLeftView:(UIImageView *)leftView showCancelButton:(BOOL)showCancelButton tintColor:(UIColor *)tintColor { 
     if (self = [super initWithFrame:frame]) {
      self.frame = frame;
      self.tintColor = tintColor; //    
      self.barTintColor = [UIColor whiteColor];
      self.placeholder = placeholder;
      self.showsCancelButton = showCancelButton;
      self.leftView = leftView; //           
      [self setImage:[UIImage imageNamed:@"clear"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal]; //           clearIcon
     }
     return self;
    }
    홈 페이지 OHHomeView Controller 를 새로 만 들 고 네 비게 이 션 표시 줄 의 title View 와 rightBarButton 을 설정 합 니 다.
    
    // navigation buttom
     UIButton *messageButton = [UIButton buttonWithType:UIButtonTypeSystem];
     [messageButton setImage:[UIImage imageNamed:@"msg"] forState:UIControlStateNormal];
     messageButton.bounds = CGRectMake(0, 0, 30, 30);
     UIBarButtonItem *messageBarButton = [[UIBarButtonItem alloc] initWithCustomView:messageButton];
     self.navigationItem.rightBarButtonItem = messageBarButton;
     
     // search bar
     UIImageView *leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"scan"]];
     leftView.bounds = CGRectMake(0, 0, 24, 24);
     self.ohSearchBar = [[OHSearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)
                placeholder:@"     "
              textFieldLeftView:leftView
               showCancelButton:NO
                tintColor:[UIColor clearColor]];
     self.navigationItem.titleView = self.ohSearchBar;
    효 과 를 살 펴 보 겠 습 니 다.왼쪽 은 iOS 9,오른쪽 iOS 11 입 니 다.

    이 럴 때 몇 가지 차 이 를 볼 수 있어 요.
    searchBar 의 높이
  • searchBar 의 textField 확대경 과 문자 위치
  • textField 의 원 각 이 일치 하지 않 습 니 다더 세심 한 것 은 textField 의 위치 가 일치 하지 않 는 다 는 것 을 발견 할 수 있다.
    해결 방법:첫 번 째 와 두 번 째 문 제 는 장치 가 iOS 11 인지 판단 하고 높이 를 설정 하 며 그렇지 않 으 면 placeholder 를 왼쪽 에 두 도록 합 니 다.핵심 코드 는 다음 과 같다.
    
    if ([[UIDevice currentDevice] systemVersion].doubleValue >= 11.0) {
      [[self.heightAnchor constraintEqualToConstant:44.0] setActive:YES];
     } else {
      [self setLeftPlaceholder];
     }
    - (void)setLeftPlaceholder {
     SEL centerSelector = NSSelectorFromString([NSString stringWithFormat:@"%@%@", @"setCenter", @"Placeholder:"]);
     if ([self respondsToSelector:centerSelector]) {
      BOOL centeredPlaceholder = NO;
      NSMethodSignature *signature = [[UISearchBar class] instanceMethodSignatureForSelector:centerSelector];
      NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
      [invocation setTarget:self];
      [invocation setSelector:centerSelector];
      [invocation setArgument:&centeredPlaceholder atIndex:2];
      [invocation invoke];
     }
    }
    세 번 째 와 네 번 째 문제 에 대해 서 는 KVC 로 textField 를 가 져 오고 맞 춤 형 으로 설정 합 니 다.textField 의 위치,크기,원 각 을 일치 시 킵 니 다.
    
    - (void)layoutSubviews{
     [super layoutSubviews];
     // search field
     UITextField *searchField = [self valueForKey:@"searchField"];
     searchField.backgroundColor = DARK_BLUE_COLOR;
     searchField.textColor = [UIColor whiteColor];
     searchField.font = [UIFont systemFontOfSize:16];
     searchField.leftView = self.leftView;
     searchField.frame = CGRectMake(0, 8, SCREEN_WIDTH, 28);
     searchField.layer.cornerRadius = 5;
     searchField.layer.masksToBounds = YES;
     [searchField setValue:[UIColor whiteColor] forKeyPath:@"placeholderLabel.textColor"];
     [self setValue:searchField forKey:@"searchField"]; 
     self.searchTextPositionAdjustment = (UIOffset){10, 0}; //      
    }
    마찬가지 로 운행 효 과 를 먼저 보 세 요.

    이번 에는 별 문제 가 없 을 줄 알 았 는데,결 과 는 그야말로 함정 이 었 다.

    textFild 의 길이,위치,원 각 이 다 르 기 때문에 여기 서 발생 하 는 문 제 를 설명 합 니 다.
    위의 그림 위의 searchBar 를 살 펴 보면 textField 왼쪽 은 원 각 이 고 오른쪽 은 직각 이 며 잘 렸 다 는 것 을 알 수 있 습 니 다.네 비게 이 션 표시 줄 title View 의 범 위 는 그 부분 으로 나 뉘 었 고 아래 의 searchBar 는 right BarButton 도 놓 치지 않 고 위 치 를 차지 했다.iOS 11 내 비게 이 션 표시 줄 의 보기 등급 변화 로 인 한 것 으로 추정 되 며,www.jianshu.com/p/352f 101d 6...또는 자체 과학 보급 에 대해 자세히 알 수 있 습 니 다.따라서 searchBar 의 size 설정 에 대해 서 는 조심해 야 합 니 다.가능 한 한 적당 한 범위 에서 제어 하 세 요.
    textField 의 원 각 은 일치 하지 않 습 니 다.원 각 크기 를 사용자 정의 하여 원 각 스타일 을 취소 합 니 다.
    
    searchField.borderStyle = UITextBorderStyleNone;
    보기 등급 을 보면 iOS 11 이하,title View 를 설정 합 니 다.x 의 기본 좌 표 는 12 이 고 iOS 11 은 0 입 니 다.따라서 textField 의 x 좌 표를 설정 하면 iOS 11 에서 12 가 더 나 와 야 일치 하 는 위치 입 니 다.
     

    코드 위의 코드 수정
    
    - (void)layoutSubviews{
     [super layoutSubviews];
     // search field
     UITextField *searchField = [self valueForKey:@"searchField"];
     searchField.backgroundColor = DARK_BLUE_COLOR;
     searchField.textColor = [UIColor whiteColor];
     searchField.font = [UIFont systemFontOfSize:16];
     searchField.leftView = self.leftView;
     if (@available(iOS 11.0, *)) {
      //       , iOS 11  searchbar x 12
      searchField.frame = CGRectMake(12, 8, SCREEN_WIDTH*0.8, 28);
    
     } else {
      searchField.frame = CGRectMake(0, 8, SCREEN_WIDTH*0.8, 28);
     }
     searchField.borderStyle = UITextBorderStyleNone;
     searchField.layer.cornerRadius = 5;
     searchField.layer.masksToBounds = YES;
     [searchField setValue:[UIColor whiteColor] forKeyPath:@"placeholderLabel.textColor"];
     [self setValue:searchField forKey:@"searchField"];
      self.searchTextPositionAdjustment = (UIOffset){10, 0}; //      
    }
    이때 가 우리 가 원 하 는 결과 다.
    첫 페이지 가 잠시 일 단락 되 었 고,이어서 우리 의 검색 페이지 를 시작 합 니 다.첫 페이지 와 달리 searchBar 와 searchController 가 함께 사용 해 야 합 니 다.OHSearchController 클래스 를 새로 만 들 고 속성 을 추가 합 니 다.
    
    @property (nonatomic, strong) OHSearchBar *ohSearchBar;
    코드 초기 화
    
    - (instancetype)initWithSearchResultsController:(UIViewController *)searchResultsController searchBarFrame:(CGRect)searchBarFrame placeholder:(NSString *)placeholder textFieldLeftView:(UIImageView *)leftView showCancelButton:(BOOL)showCancelButton barTintColor:(UIColor *)barTintColor{
     if (self = [super initWithSearchResultsController:searchResultsController]) {
      self.ohSearchBar = [[OHSearchBar alloc] initWithFrame:searchBarFrame
                 placeholder:placeholder
               textFieldLeftView:leftView
                showCancelButton:YES
                 tintColor:barTintColor];
      
      UIButton *button = [self.ohSearchBar valueForKey:@"cancelButton"];
      button.tintColor = [UIColor whiteColor];
      [button setTitle:@"  " forState:UIControlStateNormal];
      [self.ohSearchBar setValue:button forKey:@"cancelButton"];
     }
     return self;
    }
    다음은 저희 보기 컨트롤 러 OHSearchViewController 입 니 다.
    
    UIImageView *leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search"]];
     leftView.bounds = CGRectMake(0, 0, 24, 24);
     self.ohSearchController = [[OHSearchController alloc] initWithSearchResultsController:self
                       searchBarFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)
                        placeholder:@"           "
                      textFieldLeftView:leftView
                       showCancelButton:YES
                        barTintColor:BASE_BLUE_COLOR];
     
     [self.ohSearchController.ohSearchBar becomeFirstResponder];
     self.ohSearchController.ohSearchBar.delegate = self;
     [self.ohSearchController.ohSearchBar setLeftPlaceholder];
     self.navigationItem.titleView = self.ohSearchController.ohSearchBar;
     self.navigationItem.hidesBackButton = YES;
    이 단 계 를 마 친 후 대화 단계 에 이 르 렀 습 니 다.첫 페이지 의 searchBar 를 누 르 면 검색 페이지 를 뛰 어 넘 고 검색 페이지 의 취소 단 추 를 누 르 면 첫 페이지 로 돌아 갑 니 다.홈 페이지 에 searchbar 프 록 시 를 설정 하고 프 록 시 방법 을 완성 합 니 다.
    
    - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
     OHSearchViewController *ohSearchViewController = [[OHSearchViewController alloc] init];
     [self.navigationController pushViewController:ohSearchViewController animated:NO];
     return YES;
    }
    검색 페이지 에 searchbar 프 록 시 를 설정 하고 프 록 시 방법 을 완성 합 니 다.
    
    - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
     [self.navigationController popViewControllerAnimated:NO];
    }
    
    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
     [self.ohSearchController.ohSearchBar resignFirstResponder];
     //              
     UIButton *cancelBtn = [searchBar valueForKey:@"cancelButton"];
     cancelBtn.enabled = YES;
    }
    이때 문제 가 또 발생 했다.검색 페이지 의 취소 단 추 를 누 르 면 첫 페이지 로 돌아 가지 않 고 이 페이지 에 있다.하지만 화면 이 반 짝 이 는 것 을 볼 수 있다.인쇄 메 시 지 를 통 해 취소 단 추 를 누 르 고 첫 페이지 의-(BOOL)searchBar ShouldBegin Editing:(UISearch Bar*)searchBar 방법 을 실 행 했 습 니 다.곰 곰 이 생각해 보 니 첫 번 째 응답 자 를 취소 하지 않 았 고 네 비게 이 션 표시 줄 의 상호작용 체 제 를 더 해 팝 이 이전 페이지 에 도착 할 때 페이지 리 셋 을 하지 않 아서 이 문 제 를 초래 했다.해결 방법 은 첫 페이지 에서 push 검색 페이지 를 찾 을 때 첫 번 째 응답 자 를 취소 합 니 다.
    
    - (void)viewWillDisappear:(BOOL)animated {
     [self.ohSearchBar resignFirstResponder];
    }
    이것으로 큰 성 과 를 거 두 었 다.소스 코드 를 보고 깊이 이해 할 수 있 습 니 다.여러분 의 학습 에 도움 이 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.

    좋은 웹페이지 즐겨찾기