[英]UISearchController - Objective C to Swift Issue
我正在尝试对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
我遇到的问题特别与此吸气剂有关:
-(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
实例。 尽管我不确定您是否真的想要实现此目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.