以编程方式将 UISearchBar 添加到 UITableView [英] Adding UISearchBar programmatically to UITableView

查看:29
本文介绍了以编程方式将 UISearchBar 添加到 UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加一个 UISearchBar(及其相应的搜索逻辑),但有一个问题:我正在使用 UITableViewController 子类自动生成的 UITableView 而不是单独的 nib 文件,并根据表视图以编程方式操作所有内容.

I am attempting to add a UISearchBar (with its corresponding search logic) but there is a problem: I am using the UITableViewController subclass's automatically generated UITableView instead of a separate nib file, and manipulating everything programmatically in terms of the table view.

在界面生成器中,有一个选项可以将搜索栏搜索显示控制器添加到nib.有没有办法以编程方式完成同样的任务,或者放弃默认的 UITableView 并转移到自定义的 UITableView nib 文件,以便我可以轻松添加UISearchbar?

In Interface Builder, there is an option to add a Search Bar and Search Display Controller to a nib. Is there a way to accomplish this same task programmatically or is it in my favor to abandon the default UITableView and transfer to a custom UITableView nib file so that I can easily add the UISearchbar?

此外,我尝试通过 viewDidLoad 中的以下代码向我的 UITableView 标头(这是我想要的位置)添加一个搜索栏进行测试实现,但它显示在表格部分标题后面,因此是不可见的,除非表格向下滚动以显示否则为空白的内容.这是怎么回事?

Also, I have tried testing out just adding a Search Bar to my UITableView header (which is where I want it to go) via the following code in my viewDidLoad implementation, but it shows up behind table section header and hence is invisible unless the table is scrolled down to show what would otherwise be white space. What's up with this?

UISearchBar *testbar = [[UISearchBar alloc] init];

[[self tableView] setTableHeaderView:testbar];

推荐答案

设置 UISearchBar 的框架:

Set the frame for the UISearchBar:

// Change the position according to your requirements
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 70, 320, 44)];

如果您的视图是 UITableViewController 的子类,请将其更改为 UIViewController.

If your view is a subclass of UITableViewController, change it to UIViewController.

  • 在你的 nib 文件中,创建一个视图并将你的 tableView 拖到它下面查看并将该视图的参考类更改为您的UIViewController.

创建一个 UITableView * myTableViewIBOutlet 并将其连接到你的 nib 文件.你只需要在你的 VC 文件中更改例如 self 到 [self.myTableView reloadData];

Create an IBOutlet of UITableView * myTableView and connect it to your nib file. you just need to change in your VC file for example self to [self.myTableView reloadData];

现在您可以调整笔尖本身的 tableView 和搜索栏.

Now you can adjust the tableView and search bar in the nib itself.

UISearchDisplay 控制器有自己的 UITableView,它显示由另一个视图控制器管理的数据搜索结果.这里 searchDisplaycontroller 结合了搜索栏和 tableview 以在 tableview 中显示结果数据,因此它不需要单独的 tableview.

UISearchDisplay controller has its own UITableView that displays the results of a search of data managed by another view controller. Here the searchDisplaycontroller combines the search bar and tableview to show the result data in the tableview so it won't require a separate tableview.

这篇关于以编程方式将 UISearchBar 添加到 UITableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆