我正在尝试对 UISearchController 进行子类化,以便我可以添加自定义 UISearchBar。我找到了一种在 Objective-C 中执行此操作的方法,但我正在努力在 Swift 中执行此操作。以下是在 Objective-C 中实现此目的的 2 个文件:
CustomSearchController.h
@interface CustomSearchController : UISearchController <UISearchBarDelegate>
@end
CustomSearchController.m
#import "CustomSearchController.h"
#import "CustomSearchBar.h"
@implementation CustomSearchController
{
UISearchBar *_searchBar;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(UISearchBar *)searchBar {
if (_searchBar == nil) {
_searchBar = [[CustomSearchBar alloc] initWithFrame:CGRectZero];
_searchBar.delegate = self; // different from table search by apple where delegate was set to view controller where the UISearchController was instantiated or in our case where CustomSearchController was instantiated.
}
return _searchBar;
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if ([searchBar.text length] > 0) {
self.active = true;
} else {
self.active = false;
}
}
/*
Since CustomSearchController is the delegate of the search bar we must implement the UISearchBarDelegate method.
*/
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Became first responder");
[searchBar resignFirstResponder];
}
@end
我遇到的问题专门针对这个 getter:
-(UISearchBar *)searchBar {
if (_searchBar == nil) {
_searchBar = [[CustomSearchBar alloc] initWithFrame:CGRectZero];
_searchBar.delegate = self; // different from table search by apple where delegate was set to view controller where the UISearchController was instantiated or in our case where CustomSearchController was instantiated.
}
return _searchBar;
}
在 Swift
中,我相信我必须做这样的事情:
var customSearchBar: CustomSearchBar?
override var searchBar: UISearchBar {
get {
if customSearchBar == nil {
customSearchBar = CustomSearchBar()
customSearchBar?.delegate = self
}
return customSearchBar!
}
}
但这是执行此类操作的最佳方法吗?
最佳答案
试试这个:
lazy var customSearchBar: CustomSearchBar = {
[unowned self] in
let result = CustomSearchBar(frame:CGRectZero)
result.delegate = self
return result
}()
override var searchBar: UISearchBar {
get {
return customSearchBar
}
}
lazy
的用法负责仅在首次访问时初始化 CustomSearchBar
实例。尽管我不确定您是否真的需要它来实现您想要完成的目标。
关于ios - UISearchController - Objective C 到 Swift 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31524877/