When a user is entering data into a text field, it’s often nice to have the ability to automatically suggest completions for what they are entering, saving them time. For example, when you enter a URL into Safari, it will show you past URLs you have entered that you can select to save time.
Here’s how to implement this on the iPhone. First, you need to have a NSArray containing all of the data that you want to provide as potential options for the user. In this example, we’ll use an NSMutableArray of pastURLs, and every time the user browses to a URL we’ll add it to the array.
Next, we’ll need to create a view to display the URLs that the user can select from. One good way of doing this is just to create a table view below the input field that lists all of the potential options. This table view can appear only when the user is typing data into the text field, and can be hidden the rest of the time.
|
Next, we need to know when the text field is being edited so we can display the table view, and make sure the appropriate elements are in the table view. A good way to get notification that the text field is being edited is by registering your view controller as a UITextFieldDelegate and implementing the shouldChangeCharactersInRange protocol. Here’s how we’ll do it:
|
We want the table view to only show up the elements in our array that match the substring that the user has typed so far. So in our case we need to filter the pastURLs array by choosing the elements that start with the substring, and have the table view display those entries. Here’s how we’ve done this:
|
The table view just shows the contents of the autocompleteUrls, and that’s all there is to it! If you’d like to check this out for yourself, here’s a sample project.
本文介绍如何在iPhone上实现自动补全功能,通过自动完成URL输入来节省时间。首先,创建一个包含过往URL的数组。每次用户浏览到新URL时,将其添加到数组中。其次,在输入字段下方创建一个只在用户输入时显示的表格视图,用于展示用户可选择的URL选项。通过UITextFieldDelegate协议获取通知以显示表格视图,并在文本字段更改字符范围时过滤数组以匹配当前输入子字符串。

被折叠的 条评论
为什么被折叠?



