문제 설명
searchBar의 일반 텍스트 버튼에 액세스하는 방법은 무엇입니까? (How to access searchBar's clear text button?)
tableView 검색에서 "지우기" 버튼 (편집할 때 나타나는 버튼)을 눌렀을 때 키보드를 사라지게 하려고 했습니다. "지우기" 버튼을 클릭했을 때 어떻게 감지하여 firstResponder를 사임할 수 있습니까? 이미 textDidChange
메소드에서 이것을 시도했습니다:
if (SearchBar.text == @"") {
[SearchBar resignFirstResponder];
NSLog(@"clear called");
}
작동하지 않았고...또한 시도했습니다:
if (SearchBar.text == nil) {
[SearchBar resignFirstResponder];
NSLog(@"clear called");
}
두 메소드 모두 호출되었음을 보여줍니다. 어떤 아이디어가 있습니까?
편집: 이제 registeredFirstResponder가 작동하지 않는 것 같습니다. 키보드가 화면에 유지됩니다. 내가 뭘 잘못하고 있니?
참조 솔루션
방법 1:
For string comparison you should use
if([SearchBar.text isEqualToString: @""])
방법 2:
You can try watching the text
property of the search bar by registering for a KVO notification:
[self.searchBar addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:NULL];
and then implementing:
‑ (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == self.searchBar && [keyPath isEqualToString:@"text"]) {
// Handle the new value of self.searchBar.text
}
}
Edit: nevermind, answered above =)
방법 3:
I know this question is old, but another way to do this is:
if(searchText.length == 0)
in ‑ (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
(by sudo rm ‑rf、KingofBliss、Cameron Spickert、Steph Sharp)