簡體   English   中英

UISearchController-Swift的目標C

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM