UISearchController - Objective C 到 Swift 问题

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

我 运行 遇到的问题就是这个 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 实例。虽然我不确定你是否真的需要它来完成你想要完成的事情。