How to Make Uitextfield Behave Like a Uisearchbar in Swift

How to make UITextField behave like a UISearchBar in Swift?

With the help of @Daniel T. I managed to solve the problem with the following code:

func textFieldShouldReturn(textField: UITextField) -> Bool {
isFiltered = true
searchResults = prods.filter({(coisas:String) -> Bool in
let stringMatch = coisas.rangeOfString(textField.text)
return stringMatch != nil

})
println(searchResults.description)
textField.resignFirstResponder()
table.reloadData()
return true
}

Thanks @Daniel T.

Search using UITextField

There are many ways to accomplish this task.
You can place a textField as well as a UILabel exactly behind it.
And When Every you type a word just change the text of that label. Set the Label's textColor to lightGrey color and you will be good to go.
To set a method that invokes every time user type something use below code.

//Below line will set a method to textFields value change event.
searchTextField.addTarget(self, action: #selector(self.textIsChanging(textField:)), for: .editingChanged)



func textIsChanging(textField: UITextField) {

}

UISearchbar using UItextfield in swift 4

Try this:

@objc func textFieldActive() {
tableView.isHidden = tableFilterData.count > 0 ? false : true
}

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{

let searchText = textField.text! + string

if searchText.count >= 3 {
tableView.isHidden = false

tableFilterData = tabledata.filter({ (result) -> Bool in
return result.range(of: searchText, options: .caseInsensitive) != nil
})

tableView.reloadData()
}
else{
tableFilterData = []
}

return true
}

func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return tableFilterData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = tableFilterData[indexPath.row]

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

cell.textLabel?.text = data

return cell
}

How to make textfield input view as search bar?

To make Text Field work like Search Bar implement - (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
delegate method of UITextField. So basically, you need to implement AutoComplete feature and this how you do it.
To detect which textfield is triggered use assign tag to the textfield.

In your ViewController.h file:

@interface ViewController :
<UIViewController<UITextFieldDelegate,UITableViewDataSource, UITableViewDelegate>
{
UITableView *autocompleteTableView;
UITextField * searchtextField1;
UITextField * searchtextField2;
NSMutableArray *autoCompleteList;
NSMutableArray *initalList;

}

In your ViewController.m file:

- (void)viewDidLoad {
searchtextField1 = [[UITextField alloc]
initWithFrame:CGRectMake(5,0, 245, 33)];

searchtextField2.tag = 2;
searchtextFeild1.tag = 1;


searchtextField.placeholder = @"eg: make up";

searchtextField.textColor = [UIColor whiteColor];

//[imageView addSubview:searchtextField];
//[self.view addSubview:imageView];


autoCompleteList = [[NSMutableArray alloc] init];
searchtextField1.delegate = self;
searchtextField2.delegate = self;

autocompleteTableView = [[UITableView alloc]init];



if(screenRect.size.height == 568)
{
float X_Co_tbl = (self.view.frame.size.width - 271)/2;
[autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 105, 271, 120)];
}

else if (screenRect.size.width == 414)
{
float X_Co_tbl = (self.view.frame.size.width - 281)/2;
[autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 145, 281, 120)];
}
else if(screenRect.size.width == 375)
{
float X_Co_tbl = (self.view.frame.size.width - 281)/2;
[autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 125, 281, 120)];
}
else
{
float X_Co_tbl = (self.view.frame.size.width - 271)/2;
[autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 95, 271, 120)];
}
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.hidden = YES;
[self.view addSubview:autocompleteTableView];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
autocompleteTableView.hidden = YES;

return YES;
}


- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
autocompleteTableView.hidden = NO;
if (textField.tag == 1) {
/// Initialize your array for searchTextFeild1;
initialList = [[NSMutableArray alloc]initWithObjects:@"Face wash",@"Morning face wash",@"Cleanser", nil];
}
if (textField.tag == 2) {
/// Initialize your array for searchTextFeild2;
initialList = [[NSMutableArray alloc]initWithObjects:@"Face wash",@"Morning face wash",@"Cleanser", nil];
}
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring
stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}

/// You make Text Field work as Search Bar here
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {

// Put anything that starts with this substring into the autocompleteUrls array
// The items in this array is what will show up in the table view
[autoCompleteList removeAllObjects];
for(NSString *curString in initialList) {
//NSRange substringRange = [curString rangeOfString:substring];

if ([curString rangeOfString:substring options:NSCaseInsensitiveSearch].location != NSNotFound) {
[autoCompleteList addObject:curString];
}
}
[autocompleteTableView reloadData];
}

#pragma mark UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
return autoCompleteList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = @"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier];
}

cell.textLabel.text = [autoCompleteList objectAtIndex:indexPath.row];
return cell;
}

#pragma mark UITableViewDelegate methods

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

UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
searchtextField.text = selectedCell.textLabel.text;

autocompleteTableView.hidden = YES;

[self goPressed];

}

Can the height of the UISearchbar TextField be modified?


    override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
for subView in searchBars.subviews {
for subsubView in subView.subviews {
if let textField = subsubView as? UITextField {
var bounds: CGRect
bounds = textField.frame
bounds.size.height = 35 //(set height whatever you want)
textField.bounds = bounds
textField.borderStyle = UITextBorderStyle.RoundedRect
// textField.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
textField.backgroundColor = UIColor.redColor()
// textField.font = UIFont.systemFontOfSize(20)
}
}
}

}

This might helps you :)

Text Field As Search Bar

i don't know of any tutorials that covers that subject, but sometime ago with help of someone else i was able to accomplish that. here is the total code in .h and .m file. i can explain the whole thing but it is commented on each line so i guess it is clear enough.

.h

#import <UIKit/UIKit.h>

@interface SEMainVC : UIViewController <UITextFieldDelegate>{
NSMutableArray *dummyArray;
NSMutableArray *searchArray;
NSString *searchTextString;
}

@property (weak, nonatomic) IBOutlet UITextField *searchTextField;
@property (weak, nonatomic) IBOutlet UITableView *contentTableView;

- (void) setupData;

@end

.m

@interface SEMainVC ()

@end

@implementation SEMainVC

- (void)viewDidLoad
{
[super viewDidLoad];
//set the selector to the text field in order to change its value when edited
[self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//here you set up the methods to search array and reloading the tableview
[self setupData];
[self updateSearchArray];
[self.contentTableView reloadData];
}
//setting up the data sourch for the mutable array
- (void) setupData {
dummyArray = [[NSMutableArray alloc] init];

[dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"dummy 1", @"name" , @"image1.JPG", @"image" , @"dummy 1 description textview", @"description", nil]];
[dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"dummy 2", @"name" , @"image1.JPG", @"image" , @"dummy 2 description textview", @"description", nil]];
[dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"dummy 3", @"name" , @"image1.JPG", @"image" , @"dummy 3 description textview", @"description", nil]];

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

#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [searchArray 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];
}
cell.textLabel.text = [[searchArray objectAtIndex:indexPath.row] objectForKey:@"name"];
return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:@"DummyDetail" sender:[NSNumber numberWithInt:indexPath.row]];
}

#pragma mark - Search Methods

-(void)textFieldDidChange:(UITextField*)textField
{
searchTextString = textField.text;
[self updateSearchArray];
}
//update seach method where the textfield acts as seach bar
-(void)updateSearchArray
{
if (searchTextString.length != 0) {
searchArray = [NSMutableArray array];
for ( NSDictionary* item in dummyArray ) {
if ([[[item objectForKey:@"name"] lowercaseString] rangeOfString:[searchTextString lowercaseString]].location != NSNotFound) {
[searchArray addObject:item];
}
}
} else {
searchArray = dummyArray;
}

[self.contentTableView reloadData];
}

#pragma mark - Table view delegate

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(NSNumber*)indexNumber
{
if([[segue identifier] isEqualToString:@"DummyDetail"]){

NSInteger index = [indexNumber integerValue];

SEDetailVC *dummyDetail = [segue destinationViewController];
dummyDetail.dummyImageString = [[searchArray objectAtIndex:index] objectForKey:@"image"];
dummyDetail.dummyTextString = [[searchArray objectAtIndex:index] objectForKey:@"description"];
dummyDetail.title = [[searchArray objectAtIndex:index] objectForKey:@"name"];
}
}

- (void)viewDidUnload {
[self setSearchTextField:nil];
[self setContentTableView:nil];
[super viewDidUnload];
}
@end

i hope the above is clear and helpful enough, let me know if you need any assistance with it.

Search bar at the top of a UIPickerView in Swift

UIPickerView is really meant for a few options - if you need to present something that has a lot more options, I would suggest a table view with a search bar. Search Bar Tutorial is a good start.

Make uisearchbar look like uiinputfield

The following will help you attain that borderless boring look:

[searchBarObject setBackgroundImage:[UIImage new]];

//might need this as well
[searchBarObject setBackgroundColor:[UIColor clearColor]];

Note: You can continue using UISearchBarStyleDefault

or...

You could not do any of the above and instead utilize UISearchBarStyleMinimal to get a borderless but with a slight background look.

Is it possible to have UISearchBarDelegate extension in separate file?

I forgot to include UIKit.

import Foundation
import UIKit

extension HomeViewController {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//code
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
//code
}
}

Also, you need to inherit UISearchBarDelegate in ViewController, not in extension.



Related Topics



Leave a reply



Submit