4
votes

I've been trying to find the solution for hours, but alas no dice... I've been trying to implement a UISearchBar purely programatically (no xib, no interface builder).

Here is my .h header:

@interface RLCASearchMasterViewController : UIViewController<UISearchBarDelegate>

@property (strong, nonatomic) RLCAGUIElements *gui;
@property (strong, nonatomic) RLCAUITableView *table;
@property (strong, nonatomic) UISearchBar *searchBar;

@end

and my .m implementation:

@synthesize searchBar;

- (void)loadView
{

[super loadView];

searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, searchBar.frame.size.height)];
searchBar.delegate = self;
[self.view addSubview:searchBar];  

}

I'd gone over this I don't know how many times, and have no idea what I'm doing wrong... The UISearchBar is added to the view just fine, with the correct size and all, however when clicked/tapped, the keyboard does not come up. If I evoke the following however:

[searchBar becomeFirstResponder];

the keyboard does show, so it's probably not the delegation but actually detecting whether it's been clicked... I do not want it to edit on load though, and only by request...

Please help. Thanks! :)

Sincerely, Piotr.

3
Is it underneath any other views? They could be blocking its touches. - borrrden
i don't think it's under any views - i'd removed all the [UIColor clearColor] backgrounds from all the views to check, and nothing seems to be covering it... - Piotr

3 Answers

8
votes

Okay, I got it to work.

It works but I have no idea why. If someone has any insight, I would be very grateful...

So:

I replaced:

searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(self.view.frame.origin.x,         self.view.frame.origin.y, self.view.frame.size.width, searchBar.frame.size.height)];
searchBar.delegate = self;
[self.view addSubview:searchBar]; 

with:

searchBar = [[UISearchBar alloc] init];
searchBar.delegate = self;
[searchBar sizeToFit];
[self.view addSubview:searchBar];

...aaand, VIOLA! ;)

Thanks for all the answers though, and as mentioned, would appreciate an explanation why this worked and what it did.

All the best, Piotr.

2
votes
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(self.view.frame.origin.x,         self.view.frame.origin.y, self.view.frame.size.width, searchBar.frame.size.

You shouldn't access the searchBars frame for use in its own init method. I would think, since at that moment it has NOT yet been inited, it will be 0 thus giving you a rect with no height, or maybe an NSZeroRect because the makeRect failed completely

I think that's the problem.

0
votes

Try defining its delegate methods and put the becomes first responder method in the searchBarShouldBeginEditing method. If it is still not working, make sure if there is not any other view on top of this view. In this way, it will be overriding the touch.