Drag out a UISearchBar and label

Screen Shot 2017-06-03 at 2.27.29 PM.png

Hook up the outlets

Screen Shot 2017-06-03 at 2.28.00 PM.png

Implement the interface

Screen Shot 2017-06-03 at 2.28.15 PM.png

Then do this

Screen Shot 2017-06-03 at 2.28.37 PM.png

Code

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UISearchBarDelegate>


@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.searchBar.delegate = self;
}

// return NO to not become first responder
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    return YES;
}

// called when text starts editing
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    // adjust layout for keyboard display
}

// return NO to not resign first responder
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    // adjust layout for no keyboar

    return YES;
}

// called when text ends editing
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{

}

// called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    self.label.text = searchText;
}

// called when keyboard search button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.label.text = @"searchButton clicked";
}

// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    self.label.text = @"cancelButton clicked";

}

@end
Advertisements