2016-06-27 3 views
0

iOS 응용 프로그램에서 작업 중이며 내 구성 요소를 넣는 곳이 UIViewController이며 제대로 작동합니다. 이제 맞춤 설정 UIView을 만들고 내 WebView과 내 SearchController을 입력하려고합니다. 나는 성공하지 못한 채 많은 시간을 보냈다. 여기사용자 지정 WebView 및 UISearchContoller를 사용하여 사용자 지정 UIView 만들기

.m 파일이며 나는 어떤 하나를 도와 줄 수 있기를 바랍니다 :

#import "HomeViewController.h" 


#define widthtScreen [UIScreen mainScreen].bounds.size.width 
#define heightScreen [UIScreen mainScreen].bounds.size.height 


@interface HomeViewController() <UISearchResultsUpdating,UISearchBarDelegate,UIBarPositioningDelegate,UITableViewDataSource,UITableViewDelegate,MapWebViewDelegate> 

@property(strong,nonatomic) MapWebView *webView; 

@property (nonatomic) UIButton *btnGeolocate; 


@property (nonatomic, strong) UISearchController *searchController; 

@end 

@implementation HomeViewController{ 
    NSMutableArray *placesList; 
    BOOL isSearching; 
} 



-(void)loadView 
{ 
    [super loadView]; 
    self.webView = [[MapWebView alloc] initWithFrame:CGRectMake(0, -100, widthtScreen, heightScreen+100)]; 
    self.webView.mapWebViewDelegate = self; 
    [self.view addSubview:self.webView]; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 
    self.navigationItem.hidesBackButton = YES; 
    mainDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate]; 
    placesList = [[NSMutableArray alloc] init]; 
    [self initializeSearchController]; 
    mainDelegate.webView = self.webView; 


    self.btnGeolocate = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-75,550,60,60)]; 
    self.btnGeolocate.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; 
    [self.btnGeolocate setBackgroundImage:[UIImage imageNamed:@"geo.png"] 
           forState:UIControlStateNormal]; 
    [self.btnGeolocate addTarget:self action:@selector(btnGeolocatePressed:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:self.btnGeolocate]; 

    mainDelegate.btnZoomIn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-80,620,30,30)]; 
    mainDelegate.btnZoomIn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; 
    [mainDelegate.btnZoomIn setBackgroundColor:[UIColor blackColor]]; 
    [mainDelegate.btnZoomIn addTarget:self action:@selector(btnZoomInPressed:) forControlEvents:UIControlEventTouchUpInside]; 
    mainDelegate.btnZoomIn.tag=1; 
    UIImage *btnImage = [UIImage imageNamed:@"plus.png"]; 
    [mainDelegate.btnZoomIn setImage:btnImage forState:UIControlStateNormal]; 
    [self.view addSubview:mainDelegate.btnZoomIn]; 

    mainDelegate.btnZoomOut = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-40,620,30,30)]; 
    mainDelegate.btnZoomOut.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; 
    [mainDelegate.btnZoomOut setBackgroundColor:[UIColor blackColor]]; 
    [mainDelegate.btnZoomOut addTarget:self action:@selector(btnZoomOutPressed:) forControlEvents:UIControlEventTouchUpInside]; 
    mainDelegate.btnZoomOut.tag=1; 
    UIImage *btnImage2 = [UIImage imageNamed:@"minus.png"]; 
    [mainDelegate.btnZoomOut setImage:btnImage2 forState:UIControlStateNormal]; 
    [self.view addSubview:mainDelegate.btnZoomOut]; 
} 

- (BOOL)slideNavigationControllerShouldDisplayLeftMenu 
{ 
    return YES; 
} 

- (BOOL)slideNavigationControllerShouldDisplayRightMenu 
{ 
    return YES; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    NSLog(@"number :%lu",(unsigned long)[placesList count]); 
    return [placesList count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    SuggestResultObject *sro = [SuggestResultObject new]; 
    sro = [placesList objectAtIndex:indexPath.row]; 
    cell.textLabel.text = sro.textPlace; 
    return cell; 
} 

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{ 
    self.navigationItem.leftBarButtonItem = nil; 
    self.navigationItem.rightBarButtonItem =nil; 
    return true; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    self.navigationItem.leftBarButtonItem = mainDelegate.leftBarButtonItem; 
    self.navigationItem.rightBarButtonItem = mainDelegate.rightBarButtonItem; 
    SuggestResultObject *sro = [SuggestResultObject new]; 
    sro = [placesList objectAtIndex:indexPath.row]; 
    self.searchController.active = false; 
    NSString *function = [[NSString alloc] initWithFormat: @"MobileManager.getInstance().moveToLocation(\"%@\",\"%@\")", sro.latPlace,sro.lonPlace]; 
    [_webView evaluateJavaScript:function completionHandler:nil]; 
} 



- (void)jsRun:(NSString *) searchText { 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     NSString *function = [[NSString alloc] initWithFormat: @"MobileManager.getInstance().setSuggest(\"%@\")", searchText]; 
     [_webView evaluateJavaScript:function completionHandler:nil]; 
    }); 
} 

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar { 
    isSearching = YES; 
} 

- (void)initializeSearchController { 
    UITableViewController *searchResultsController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain]; 
    searchResultsController.tableView.dataSource = self; 
    searchResultsController.tableView.delegate = self; 
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController]; 
    self.definesPresentationContext = YES; 
    self.searchController.hidesNavigationBarDuringPresentation = false; 
    self.searchController.accessibilityElementsHidden= true; 
    self.searchController.dimsBackgroundDuringPresentation = true; 
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0); 
    self.navigationItem.titleView = self.searchController.searchBar; 
    self.searchController.searchResultsUpdater = self; 
    self.searchController.searchBar.delegate = self; 
} 

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { 
    self.navigationItem.leftBarButtonItem = mainDelegate.leftBarButtonItem; 
    self.navigationItem.rightBarButtonItem = mainDelegate.rightBarButtonItem; 
    NSLog(@"Cancel clicked"); 
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; 
    [placesList removeAllObjects]; 
} 


-(void)updateSearchResultsForSearchController:(UISearchController *)searchController { 
    [placesList removeAllObjects]; 
    if([searchController.searchBar.text length] != 0) { 
     isSearching = YES; 
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 
     [self jsRun:searchController.searchBar.text]; 
    } 
    else { 
     isSearching = NO; 
     [((UITableViewController *)self.searchController.searchResultsController).tableView reloadData]; 
    } 
} 

-(void) btnGeolocatePressed : (id) sender{ 
} 

-(void) btnZoomInPressed : (id) sender{ 
    [_webView evaluateJavaScript:@"MobileManager.getInstance().zoomIn();" completionHandler:nil]; 
} 

-(void) btnZoomOutPressed : (id) sender{ 
    [_webView evaluateJavaScript:@"MobileManager.getInstance().zoomOut();" completionHandler:nil]; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (void)searchResult:(NSArray*)dataArray{ 
    SuggestResultObject *sro = [SuggestResultObject new]; 
    sro.textPlace = [dataArray objectAtIndex:0]; 
    sro.lonPlace = [dataArray objectAtIndex:1]; 
    sro.latPlace = [dataArray objectAtIndex:2]; 
    [placesList addObject:sro]; 
    [((UITableViewController *)self.searchController.searchResultsController).tableView reloadData]; 
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; 
} 
@end 
+0

안녕 OP, 그것은 도움이 될에 .. UINavigationController에 포함 UIViewController 아래로 테스트 " 여기 내 코드 "도움말"입니다. – Brandon

+0

문제는 uisearchcontroller를 uisviewcontroller로 사용자 지정 uiview에 넣고 uiviewcontroller에서 호출하려고하지만 뷰에서 NavController를 사용할 수 없기 때문에 내가 만들지 못했기 때문입니다. 수동으로 작동하지 않습니다. –

+0

@OP; NavigationController에 포함 된 UIViewController에 포함 된 UIWebView 및 UISearchController를 원하십니까? 또는 UIView에 포함 된 NavigationController에 포함 된 UIWebView 및 UISearchController를 원하십니까? – Brandon

답변

0

스크린 샷 (유래에서 이미지의 크기를 조절하는 방법을 잘하지 .. OSX는 망막 형식으로 이미지를 소요가 상당히 큰 것 ! 미리 죄송합니다)!

http://i.imgur.com/15qxDpc.png

http://i.imgur.com/QHduP07.png

어떻게 작동합니까? UIView과 두 개의 하위보기 : UITableViewUIWebView을 만듭니다. 올바르게 구속하십시오.

메서드의 매개 변수로 nil SearchResultsController 을 사용하여 UISearchController을 만듭니다.

그러면 검색 컨트롤러에서 결과가 이 현재 컨트롤러 /보기에 표시됨을 알 수 있습니다.

다음으로 우리는 UISearchController에 대한 대리자를 설정하고 필터링 기능을 만듭니다.

보기가 생성되었으므로 UIViewController에서 으로 테스트해야합니다. 우리는

다음

, 내가 UINavigationController에 추가하기로 선택한 ... 하나가있는 경우있는 navigationController에있는 tableView 헤더 또는 에 검색 창을 추가 할 수 있습니다 나는 가에있는 탐색 모음을 숨길하기 위해 UISearchController 말했다 프리젠 테이션.

그런 식으로 결과는 탐색 모음 을 숨기지 않고 현재보기에 표시됩니다.

당신은 자바 스크립트 대신 UIWebView을 실행하기 위해 JSContext를 사용하는

그러나, 더 나은 아이디어가 될 것이다 .. 다음 숨겨진 웹보기를 사용할 수 있으며 오프 스크린 당신이 그것을 사용하는 어떤 자바 스크립트 검색을 수행 할 수 . UIWebView 의 장점은 HTML을 구문 분석하고 JSContext 이 허용하지 않는 DOM을 수정할 수 있다는 것입니다. 어쨌든

.. 여기

내가 UINavigationController에 포함 된 UIViewController에 추가 한 다음 UISearchControllerUIWebView를 포함 .. 그리고 UIView을 위해 쓴 코드입니다.

// 
// SearchView.h 
// StackOverflow 
// 
// Created by Brandon T on 2016-06-26. 
// Copyright © 2016 XIO. All rights reserved. 
// 

#import <UIKit/UIKit.h> 

@class SearchView; 

@protocol SearchViewDelegate <UISearchBarDelegate> 
- (void)didSelectRowAtIndexPath:(SearchView *)searchView tableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath; 
@end 

@interface SearchView : UIView 
@property (nonatomic, weak) id<SearchViewDelegate> delegate; 
- (UISearchBar *)getSearchBar; 
- (UIWebView *)getWebView; 
@end 


// 
// SearchView.m 
// StackOverflow 
// 
// Created by Brandon T on 2016-06-26. 
// Copyright © 2016 XIO. All rights reserved. 
// 

#import "SearchView.h" 

#define kTableViewCellIdentifier @"kTableViewCellIdentifier" 

@interface SearchView() <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating> 
@property (nonatomic, strong) UIWebView *webView; 
@property (nonatomic, strong) UISearchController *searchController; 
@property (nonatomic, strong) UITableView *tableView; 
@property (nonatomic, strong) NSArray *dataSource; 
@property (nonatomic, strong) NSArray *searchResults; 
@end 

@implementation SearchView 

- (instancetype)init { 
    if (self = [super init]) { 

     [self setupData]; 
     [self initControls]; 
     [self themeControls]; 
     [self registerCells]; 
     [self doLayout]; 
    } 
    return self; 
} 

- (UISearchBar *)getSearchBar { 
    return _searchController.searchBar; 
} 

- (UIWebView *)getWebView { 
    return _webView; 
} 

- (void)setDelegate:(id<SearchViewDelegate>)delegate { 
    _delegate = delegate; 
    _searchController.searchBar.delegate = delegate; 
} 

- (void)setupData { 
    //Begin fake data 

    _dataSource = @[@"Cat", @"Dog", @"Bird", @"Parrot", @"Rabbit", @"Racoon", @"Rat", @"Hamster", @"Pig", @"Cow"]; 

    //End fake data 


    _searchResults = [_dataSource copy]; 
} 

- (void)initControls { 
    _webView = [[UIWebView alloc] init]; 
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; 
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain]; 
} 

- (void)themeControls { 
    [_webView setHidden:YES]; 

    [_tableView setDelegate:self]; 
    [_tableView setDataSource:self]; 

    _searchController.searchResultsUpdater = self; 
    _searchController.dimsBackgroundDuringPresentation = false; 
    _searchController.definesPresentationContext = true; 
    _searchController.hidesNavigationBarDuringPresentation = false; 
} 

- (void)registerCells { 
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kTableViewCellIdentifier]; 
} 

- (void)doLayout { 
    [self addSubview:_webView]; 
    [self addSubview:_tableView]; 

    NSDictionary *views = @{@"webView":_webView, @"tableView": _tableView}; 
    NSMutableArray *constraints = [[NSMutableArray alloc] init]; 

    [constraints addObject:[NSString stringWithFormat:@"H:|-(%d)-[webView]-(%d)-|", 0, 0]]; 
    [constraints addObject:[NSString stringWithFormat:@"H:|-(%d)-[tableView]-(%d)-|", 0, 0]]; 

    [constraints addObject:[NSString stringWithFormat:@"V:|-(%d)-[webView(%d)]-(%d)-[tableView]-(%d)-|", -100, 100, 0, 0]]; 

    for (NSString *constraint in constraints) { 
     [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraint options:0 metrics:nil views:views]]; 
    } 

    for (UIView *view in self.subviews) { 
     [view setTranslatesAutoresizingMaskIntoConstraints:NO]; 
    } 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return _searchController.active && _searchController.searchBar.text.length > 0 ? [_searchResults count] : [_dataSource count]; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    return 50; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellIdentifier forIndexPath:indexPath]; 

    if (_searchController.active && _searchController.searchBar.text.length > 0) { 
     cell.textLabel.text = _searchResults[indexPath.row]; 
    } 
    else { 
     cell.textLabel.text = _dataSource[indexPath.row]; 
    } 

    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectRowAtIndexPath:tableView:indexPath:)]) { 
     [self.delegate didSelectRowAtIndexPath:self tableView:tableView indexPath:indexPath]; 
    } 
} 


- (void)updateSearchResultsForSearchController:(UISearchController *)searchController { 
    [self filterResults:searchController.searchBar.text scope:nil]; 
} 

- (void)filterResults:(NSString *)searchText scope:(NSString *)scope { 
    _searchResults = [_dataSource filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) { 

     NSString *object = [evaluatedObject uppercaseString]; 
     return [object rangeOfString:[searchText uppercaseString]].location != NSNotFound; 
    }]]; 

    [_tableView reloadData]; 
} 

@end 

은 그 때 나는 당신이 실제로 문제가 대신 무엇인지 우리에게 말했다 경우

// 
// ViewController.m 
// StackOverflow 
// 
// Created by Brandon T on 2016-06-26. 
// Copyright © 2016 XIO. All rights reserved. 
// 

#import "ViewController.h" 
#import "SearchView.h" 


@interface ViewController()<SearchViewDelegate> 
@property (nonatomic, strong) SearchView *searchView; 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [self initControls]; 
    [self themeControls]; 
    [self doLayout]; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
} 


- (void)initControls { 
    _searchView = [[SearchView alloc] init]; 
} 

- (void)themeControls { 
    self.edgesForExtendedLayout = UIRectEdgeNone; 
    self.navigationItem.titleView = [_searchView getSearchBar]; 

    [_searchView setDelegate:self]; 
} 

- (void)doLayout { 
    [self.view addSubview:_searchView]; 

    NSDictionary *views = @{@"searchView":_searchView}; 
    NSMutableArray *constraints = [[NSMutableArray alloc] init]; 

    [constraints addObject:[NSString stringWithFormat:@"H:|-%d-[searchView]-%d-|", 0, 0]]; 
    [constraints addObject:[NSString stringWithFormat:@"V:|-%d-[searchView]-%d-|", 0, 0]]; 

    for (NSString *constraint in constraints) { 
     [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraint options:0 metrics:nil views:views]]; 
    } 

    for (UIView *view in self.view.subviews) { 
     [view setTranslatesAutoresizingMaskIntoConstraints:NO]; 
    } 
} 

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar { 
    self.navigationItem.leftBarButtonItems = nil; 
    self.navigationItem.rightBarButtonItems = nil; 
} 

- (void)didSelectRowAtIndexPath:(SearchView *)searchView tableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath { 

    [[searchView getWebView] stringByEvaluatingJavaScriptFromString:@"SomeJavascriptHere"]; 

} 
@end 
+0

큰 덕분에 남자 - (UISearchBar *) getSearchBar { 반환 _searchController.searchBar; } 이것은 내 코드에서 누락 된 기능입니다. –

+0

검색 막대를 클릭하고 입력 할 때 몇 가지 테스트를 마친 후. 그것은 사라집니다 –

+0

내가 게시 한 코드는 검색 막대를 숨기지 않으므로 : '_searchController.hidesNavigationBarDuringPresentation = false;'이고 검색 막대는 탐색 막대에 있습니다. – Brandon