当我在searchcontroller的搜索栏中输入内容时,取消按钮会自动隐藏,我该如何阻止?

时间:2016-08-13 07:44:27

标签: uisearchbar uisearchcontroller

这是我的搜索条形码。我输入取消按钮有问题,因为我输入了取消按钮擦除的东西。如何显示取消按钮?

//
//  HomePageViewController.m
//  LiveVideoStreaming
//
//  Created by Bodacious IT Hub on 14/06/16.
//  Copyright © 2016 SHUBHAM GUPTA. All rights reserved.
//

#import "HomePageViewController.h"
#import "VideoTableViewCell.h"
#import "PeopleTableViewCell.h"
#import "FollowingTableViewCell.h"
#import "ViewerViewController.h"
#import "MyTableViewController.h"
#import "webservice.h"

@interface HomePageViewController ()

@property (weak, nonatomic) IBOutlet UIBarButtonItem *moreBtn;


@property (strong, nonatomic) UISearchController *searchController;

@property (strong, nonatomic) NSArray *searchResults;

@property BOOL searchControllerWasActive;
@property BOOL searchControllerSearchFieldWasFirstResponder;



@property BOOL shouldShowSearchResults;

@end

@implementation HomePageViewController
{
    ViewerViewController *viewVideo;
    NSInteger index;

    NSArray *items;
    CarbonTabSwipeNavigation *carbonTabSwipeNavigation;

    MyTableViewController *myTableView;

    UIStoryboard *storyBoard;
    VideoTableViewCell *video;


    NSArray<MyTableViewController *> *viewControllersCollection;

    NSUInteger selectedViewControllerIndex;

    NSArray *searchedArray;


    BOOL isScrolling;
    BOOL fullvisible;

    NSMutableArray *Username;
    NSString *searchText;
    NSMutableArray* captionList;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _shouldShowSearchResults = false;

    Username = [[NSMutableArray alloc]init];

    items = @[

              @"Video",@"People",@"Following"
              ];

    captionList = [[NSMutableArray alloc] initWithObjects:@"#musicians",@"#dance",@"#girls",@"#bored",@"#guys",@"#ask_questions",@"#random",@"#singing",@"#girl",@"#musical.ly",@"#talk",@"#lgbt",@"#-bored",@"#truthordare",@"#chill",@"#alternative",@"#humor",@"#gaming",@"#sleepingsquad",@"#beauty",@"#advice",@"#advice",@"#youtuber",@"#music",@"#art",@"#hiphop",@"#makeup",@"#pets",@"#dj",@"#parents",@"#cooking", nil];



    myTableView.myTable.showsVerticalScrollIndicator = false;


    MyTableViewController *videoVC = [self.storyboard instantiateViewControllerWithIdentifier:@"myTableViewController"];

    MyTableViewController *peopleVC = [self.storyboard instantiateViewControllerWithIdentifier:@"myTableViewController"];

    videoVC.homePage = self;
    peopleVC.homePage = self;

    peopleVC.AllUsers = _allUsers;

    videoVC.array = _Array;

    for(int i=0;i<_allUsers.count;i++){

        NSDictionary *dict = [NSDictionary dictionaryWithDictionary:_allUsers[i]];

        NSString *user = [dict objectForKey:@"Username"];

        [Username addObject:user];
    }

    MyTableViewController *followingVC = [self.storyboard instantiateViewControllerWithIdentifier:@"myTableViewController"];

    viewControllersCollection = @[videoVC, peopleVC, followingVC];

    videoVC.option = VIDEO;
    peopleVC.option = PEOPLE;

    followingVC.option = FOLLOWING;

    carbonTabSwipeNavigation = [[CarbonTabSwipeNavigation alloc] initWithItems:items delegate:self];
    [carbonTabSwipeNavigation insertIntoRootViewController:self];






}



- (void)style {

    UIColor *color = [UIColor colorWithRed:82.0 / 255 green:152.0 / 255 blue:252.0 / 255 alpha:1];


    carbonTabSwipeNavigation.toolbar.translucent = NO;

    [carbonTabSwipeNavigation setIndicatorColor:color];

    CGFloat width = self.view.frame.size.width/3;

    [carbonTabSwipeNavigation setTabExtraWidth:self.view.frame.size.width/3];
    [carbonTabSwipeNavigation.carbonSegmentedControl setWidth:width forSegmentAtIndex:0];
    [carbonTabSwipeNavigation.carbonSegmentedControl setWidth:width forSegmentAtIndex:1];
    [carbonTabSwipeNavigation.carbonSegmentedControl setWidth:width forSegmentAtIndex:2];

    // Custimize segmented control
    [carbonTabSwipeNavigation setNormalColor:[color colorWithAlphaComponent:0.6]
                                        font:[UIFont boldSystemFontOfSize:14]];
    [carbonTabSwipeNavigation setSelectedColor:color font:[UIFont boldSystemFontOfSize:20]];
}


#pragma mark - CarbonTabSwipeNavigation Delegate
// required
- (nonnull UIViewController *)carbonTabSwipeNavigation:
(nonnull CarbonTabSwipeNavigation *)carbontTabSwipeNavigation
                                 viewControllerAtIndex:(NSUInteger)Index {

    return  viewControllersCollection[Index];
}



- (void)carbonTabSwipeNavigation:(nonnull CarbonTabSwipeNavigation *)carbonTabSwipenavigation
                  didMoveAtIndex:(NSUInteger)Index {



    selectedViewControllerIndex = Index;

    //    self.navigationController.navigationBar.barTintColor = [self randomColor];
}


-(void)viewDidLayoutSubviews{

    if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) {

        [self style];
    }

    else{

        [self style];

    }


}


-(void)viewWillAppear:(BOOL)animated{


    [self configureSearchController];

    [super viewWillAppear:animated];

    carbonTabSwipeNavigation.carbonSegmentedControl.selectedSegmentIndex = selectedViewControllerIndex;





    _moreBtn.tintColor = [UIColor whiteColor];

    [self.navigationItem setHidesBackButton:YES animated:YES];

    self.navigationController.navigationBarHidden = false;

    [self style];




}



-(void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];


    //    [carbonTabSwipeNavigation removeFromParentViewController];


}

- (UIBarPosition)barPositionForCarbonTabSwipeNavigation:
(nonnull CarbonTabSwipeNavigation *)carbonTabSwipeNavigation {
    return UIBarPositionTop; // default UIBarPositionTop
}

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

/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */







-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{


    UITouch *t = [touches anyObject];
    UIView *v = t.view;


    [self.view endEditing:YES];


}

此处我的搜索栏文字更新,但之后我的搜索栏取消按钮隐藏。

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{

    searchText = _searchController.searchBar.text;


    _shouldShowSearchResults = true;

    _displayItems = [[NSArray alloc]init];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{


        if (selectedViewControllerIndex == 0) {

            if ([searchText  containsString:@"#"] && selectedViewControllerIndex == 0) {


                viewControllersCollection[0].hastagFlag = true;
                viewControllersCollection[0].searchingFlag = true;
                viewControllersCollection[0].nameSearch = false;

                _displayItems = captionList;

                viewControllersCollection[0].searchingFlag = false;

                [viewControllersCollection[selectedViewControllerIndex] setDisplayItems:_displayItems searchResult:_shouldShowSearchResults];



            }

            else{

                viewControllersCollection[0].hastagFlag = false;
                viewControllersCollection[0].searchingFlag = true;

                viewControllersCollection[0].nameSearch = true;
                //            NSPredicate *Predicate =
                //            [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchText];

                if (![searchText isEqualToString:@""]) {

                    [self search];


                }

                else{

                    _displayItems = _Array;
                }


                viewControllersCollection[0].searchingFlag = false;


                [viewControllersCollection[selectedViewControllerIndex] setDisplayItems:_displayItems searchResult:_shouldShowSearchResults];

                [viewControllersCollection[0] showData];
            }
        }


        else if(selectedViewControllerIndex == 1){

            //        [self setSearchBartext:searchText];


            viewControllersCollection[1].hastagFlag = false;
            viewControllersCollection[1].searchingFlag = true;

            viewControllersCollection[1].nameSearch = true;
            //            NSPredicate *Predicate =
            //            [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchText];

            if (![searchText isEqualToString:@""]) {

                [self searchAllPeople];


            }

            else{

                _displayItems = _allUsers;
            }


            viewControllersCollection[1].searchingFlag = false;


            [viewControllersCollection[selectedViewControllerIndex] setDisplayItems:_displayItems searchResult:_shouldShowSearchResults];

            [viewControllersCollection[1] showData];

        }
    });


}





-(void)search{

    dispatch_async(dispatch_get_main_queue(), ^{

        [viewControllersCollection[0].act startAnimating];


    });



    NSString *urlstring = [searchVideos stringByAppendingString:[NSString stringWithFormat:@"searchText=%@&option=live",searchText]];

    urlstring = [urlstring stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL *ur= [[NSURL alloc] initWithString:urlstring];


    NSURLRequest * urlRequest = [NSURLRequest requestWithURL:ur];
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];


    //    [NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:ur] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {

    }
    else {

        [self getSearchedObject:data];

    }


}


-(void)searchAllPeople{


    dispatch_async(dispatch_get_main_queue(), ^{

        [viewControllersCollection[1].act startAnimating];


    });



    NSString *urlstring = [searchVideos stringByAppendingString:[NSString stringWithFormat:@"searchText=%@&option=AllUsers",searchText]];

    urlstring = [urlstring stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL *ur= [[NSURL alloc] initWithString:urlstring];


    NSURLRequest * urlRequest = [NSURLRequest requestWithURL:ur];
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];


    //    [NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:ur] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {

    }
    else {

        id object = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

        searchedArray = [[NSArray alloc]initWithArray:object];

        _displayItems = searchedArray;

        dispatch_async(dispatch_get_main_queue(), ^{

            [viewControllersCollection[1].act stopAnimating];

        });
    }

}


-(void)getSearchedObject:(NSData*)data{


    id object = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    searchedArray = [[NSArray alloc]initWithArray:object];

    _displayItems = searchedArray;

    dispatch_async(dispatch_get_main_queue(), ^{

        [viewControllersCollection[0].act stopAnimating];

    });



}



#pragma mark - UISearchControllerDelegate

// Called after the search controller's search bar has agreed to begin editing or when
// 'active' is set to YES.
// If you choose not to present the controller yourself or do not implement this method,
// a default presentation is performed on your behalf.
//
// Implement this method if the default presentation is not adequate for your purposes.
//
- (void)presentSearchController:(UISearchController *)searchController {

}

- (void)willPresentSearchController:(UISearchController *)searchController {
    // do something before the search controller is presented
}

- (void)didPresentSearchController:(UISearchController *)searchController {
    // do something after the search controller is presented
}

- (void)willDismissSearchController:(UISearchController *)searchController {
    // do something before the search controller is dismissed
}

- (void)didDismissSearchController:(UISearchController *)searchController {
    // do something after the search controller is dismissed
}





-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

    [self.view endEditing:YES];
}



-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{

    viewControllersCollection[selectedViewControllerIndex].searchingFlag = false;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [viewControllersCollection[selectedViewControllerIndex] refreshTable];
    });


}


-(void)configureSearchController{

    _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];


    _searchController.searchBar.delegate = self;

    self.definesPresentationContext = YES;

    [_searchController.searchBar sizeToFit];

    _searchController.searchResultsUpdater = self;

    self.searchController.hidesNavigationBarDuringPresentation = false;


    _searchController.dimsBackgroundDuringPresentation = false;

    [_searchController.searchBar setTintColor:[UIColor whiteColor]];

    self.navigationItem.titleView = _searchController.searchBar;
}




-(void)viewDidDisappear:(BOOL)animated{


    [super viewDidDisappear:animated];


    [_searchController.searchBar removeFromSuperview];
}



-(void)getProfilePic{


    NSString* uname = [[NSUserDefaults standardUserDefaults]stringForKey:@"Username"];

    NSString* filename = [NSString stringWithFormat:@"%@_profile.png",uname];

    NSString *filePath = [self documentsPathForFileName:filename]; //

    BOOL fileExist = [[NSFileManager defaultManager]fileExistsAtPath:filePath];

    if (fileExist) {

        NSData *imageData = [NSData dataWithContentsOfFile:filePath];

        UIImage *profileImage = [UIImage imageWithData:imageData];



    }

    else{

        UIImage *imageProfile = [UIImage imageNamed:@"profile"];

        NSData* pngData = UIImagePNGRepresentation(imageProfile);

        [pngData writeToFile:filePath atomically:YES]; //Write the file

    }


}



- (NSString *)documentsPathForFileName:(NSString *)name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];

    return [documentsPath stringByAppendingPathComponent:name];
}



-(void)setSearchBartext:(NSString *)searchTExt{


    if (viewControllersCollection[0].hastagFlag) {
        dispatch_async(dispatch_get_main_queue(), ^{

            _searchController.searchBar.text = searchTExt;

        });
    }

    else{

        _searchController.searchBar.text = searchTExt;


    }


}



-(void)endSearching:(BOOL)searchingflag{


    if (searchingflag == true) {

        self.searchController.searchBar.showsCancelButton = false;
    }
}
@end

0 个答案:

没有答案
相关问题