Ios UISearchBar显示问题

Ios UISearchBar显示问题,ios,uisearchbar,Ios,Uisearchbar,搜索栏的右边缘比左边缘宽,我不知道为什么?这不酷。请帮帮我。非常感谢 这是我的密码: @property (nonatomic, strong) UITableView *tableView; @property (nonatomic, strong) UISearchBar *searchBar; @property (nonatomic, strong) UISearchDisplayController *strongSearchDisplayController; self.searc

搜索栏的右边缘比左边缘宽,我不知道为什么?这不酷。请帮帮我。非常感谢

这是我的密码:

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UISearchDisplayController *strongSearchDisplayController;

self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
self.searchBar.backgroundColor = [UIColor clearColor];
self.searchBar.placeholder = @"搜索";
self.searchBar.delegate = self;
[self.searchBar sizeToFit];

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, SCREENWIDTH, SCREENHEIGHT - NAVIGATIONBARHEIGHT - TABBARHEIGHT ) style:UITableViewStylePlain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];

self.tableView.tableHeaderView = self.searchBar;
self.strongSearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.searchResultsDelegate = self;
self.searchDisplayController.delegate = self;
self.searchDisplayController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

我的建议是通过以下方式实现搜索栏框架:

CGRectZero等价于(0,0,0,0)

此外,最好将搜索栏添加到视图中。像这样:

- (void) viewDidLoad:(BOOL)animated {

UIView *searchbarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)]; //This adds a container that will hold the search bar. 
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)]; 
self.searchBar.delegate = self;
[searchbarView addSubview:self.searchBar];
self.tableView.tableHeaderView = searchbarView; //Inserts UIView into the header of self.tableView
}

您可以进行以下操作:

向表格中添加与搜索栏高度相等的顶部偏移:

self.tableView.contentInset = UIEdgeInsetsMake(searchController.searchBar.frame.height, 0, 0, 0);
将搜索栏直接添加到tableView,而不是tableHeaderView:

// remove this
self.tableView.tableHeaderView = self.searchBar;

// insert this
[self.tableView addSubview:self.searchBar];
请确保searchBar rect具有正确的原点(0,0)


注意:这将解决您的问题,但搜索栏的行为将与原来的有所不同:搜索栏默认可见,半关闭时不会自动隐藏搜索栏,等等。

您将搜索栏设置为表视图的标题视图,并显示索引,这就是为什么它会这样显示您。如果你把它移出表视图,你会看到它看起来很好。@Adelurrehman嗨,搜索栏必须是表视图的标题视图。所以,我不知道如何解决这个问题。谢谢。@AdeeUrRehman可能是jxdwinter想要这样的@Jageen是的。这正是我想要的。我将搜索栏放在uiview中,并将该视图作为talbeview的标题视图。开始时看起来不错,但当我点击搜索栏,然后单击“取消”按钮时,它看起来与上图相同-(@jxdwinter您能上传示例项目吗?这样可以节省我在我的环境中产生问题的时间