Uisearchbar占位符文本 - 编程中心与中心保持一致



我使用 UISearchBar用于搜索目的。我需要将搜索栏的占位符文本对齐到搜索栏的中心,当用户开始键入时,文本必须为左对齐。

预先感谢

我以前有一个类似于您的问题。我找不到任何解决方法,毕竟我只使用了UILabelUISearchBarDelegate方法。

viewController.h:

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UISearchBarDelegate>
@end

viewController.m:

#import "ViewController.h"
@interface ViewController () {
    UISearchBar *srchBar;
    UILabel *customPlaceHolderForSearchBar;
}
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    CGRect frm = CGRectMake(0, 0, self.view.frame.size.width, 80);
    srchBar = [[UISearchBar alloc] initWithFrame:frm];
    srchBar.delegate = self;
    [self.view addSubview:srchBar];
    customPlaceHolderForSearchBar = [[UILabel alloc] initWithFrame:frm];
    customPlaceHolderForSearchBar.text = @"PlaceHolder text";
    customPlaceHolderForSearchBar.textColor = [UIColor grayColor];
    customPlaceHolderForSearchBar.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:customPlaceHolderForSearchBar];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    customPlaceHolderForSearchBar.hidden = YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    if (searchBar.text.length < 1) {
        customPlaceHolderForSearchBar.hidden = NO;
    }
}
@end

最新更新