iOS 맞 춤 형 UISearchBar 내 비게 이 션 표시 줄 iOS 11 동기 화 방법
일부 주류 앱 도 네 비게 이 션 표시 줄 에 searchBar 를 삽입 하 는 경우 가 많다.왕 이 클 라 우 드 음악 과 아 는 것 을 예 로 들 면 왼쪽 은 홈 페이지 이 고 오른쪽 은 검색 페이지(커서 주의)이다.
사고 와 사례 를 실현 하 다.
핵심 사상 은 네 비게 이 션 표시 줄 의 title View 와 좌우 의 barButton Item 을 설정 하 는 것 이다.주로 세 가지 방식 이 있어 요.
케이스
왕 이 클 라 우 드 음악 홈 페이지 와 검색 페이지 의 네 비게 이 션 바 보기 등급,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 의 높이
해결 방법:첫 번 째 와 두 번 째 문 제 는 장치 가 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:¢eredPlaceholder 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];
}
이것으로 큰 성 과 를 거 두 었 다.소스 코드 를 보고 깊이 이해 할 수 있 습 니 다.여러분 의 학습 에 도움 이 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Swift의 패스트 패스Objective-C를 대체하기 위해 만들어졌지만 Xcode는 Objective-C 런타임 라이브러리를 사용하기 때문에 Swift와 함께 C, C++ 및 Objective-C를 컴파일할 수 있습니다. Xcode는 S...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.