Ios UISearchController-目标C到Swift问题

Ios UISearchController-目标C到Swift问题,ios,objective-c,swift,uisearchbar,uisearchcontroller,Ios,Objective C,Swift,Uisearchbar,Uisearchcontroller,我正在尝试对UISearchController进行子类化,以便添加自定义UISearchBar。我在Objective-C中找到了这样做的方法,但在Swift中我很难做到。以下是在Objective-C中实现此目标的两个文件: CustomSearchController.h @interface CustomSearchController : UISearchController <UISearchBarDelegate> @end 我遇到的问题就是这个getter: -(

我正在尝试对UISearchController进行子类化,以便添加自定义UISearchBar。我在Objective-C中找到了这样做的方法,但在Swift中我很难做到。以下是在Objective-C中实现此目标的两个文件:

CustomSearchController.h

@interface CustomSearchController : UISearchController <UISearchBarDelegate>

@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
的使用才负责初始化
CustomSearchBar
实例。尽管我不确定您是否真的需要它来完成您想要完成的任务。

不要忘记在getter中使用
assert(customSearchBar!=nil,“customSearchBar为nil!”)
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
    }
}