How to left align UISearchBar placeholder text

Viewed 28808

This is the searchbar that the designers want me to create

I need to make a custom search bar like this. The problem I am having is left aligning the placeholder text, as well as placing the search icon in the right. I have a png of the search icon that I have tried to use in an UIImageView, and set that UIImageView as the rightView of the UISearchBar's UITextField. This solution has not worked, and I ran out of ideas. Does anyone have a solution?

10 Answers

Don't use a UISearchBar if you need to do these kinds of customizations. You'll have to make your own using a UITextField and a UIImageView, and responding to the delegate calls.

If you want your control to respond exactly how you want, you should probably make your own custom control. This control could be separated in three parts :

  1. a background UIImageView
  2. a UITextField
  3. a UIButton for the the search icon if you want the user to interact with it

The easiest way to do that is probably to create a new class MySearchBar, with the three parts in the private interface :

@interface MySearchBar ()
@property (nonatomic, strong) UISearchBar* searchBar;
@property (nonatomic, strong) UITextField* textField;
@property (nonatomic, strong) UIButton* button;
@end

In your MySearchBar, you can create your component, customize it, add a better look & feel. To get back the search result, your control can have a delegate id<UISearchBarDelegate> (your UIViewController) which will basically simulate having a standard UISearchBar.

What remains is to create your MySearchBar in your controller and set the delegate to your view controller. The messages from the UISearchBarDelegate can either go to your MySearchBar to filter or do pre-treatment before sending to your UIViewController, or go directly to your UIViewController.

it could be done from story board there is combo box with name semantic on attribute inspector of search bar if you set it to force right to left its done you have right align search bar and it has a similar thing for aligning from left

Related