by Emrick Sinitambirivoutin

由Emrick Sinitambirivoutin

如何在Swift中使用CoreData设置有用的自动完成UITextField (How to setup a helpful auto-complete UITextField using CoreData in Swift)

使用UITableView和CoreData构建自动完成搜索栏所需的全部知识。 (All you need to know to build your autocompletion search bar with a UITableView and CoreData.)

In this article, I’m going to present how I built a custom search field with an autocompletion feature to retrieve data from CoreData. It’s a component that I needed in one of my apps and that can be very useful in many cases to improve the user’s experience.

在本文中,我将介绍如何构建具有自动补全功能的自定义搜索字段以从CoreData检索数据。 这是我的一个应用程序中需要的一个组件,在许多情况下对改善用户体验非常有用。

我们会看到: (We will see:)

  • How to set up a simple app with a search UITextField
    如何使用搜索UITextField设置简单的应用程序
  • How to configure a TableView to show the search results
    如何配置TableView以显示搜索结果
  • How to make real-time queries to CoreData collections
    如何对CoreData集合进行实时查询

1.建立项目 (1. Setting up the project)

Just create a single view App with the following components (check CoreData at the project creation !). To be more concrete, let’s imagine this is for a travel recommendation App and the user needs to provide a city name to get all the information of the place.

只需创建具有以下组件的单个视图应用程序即可(在创建项目时检查CoreData!)。 更具体地说,让我们想象一下这是一个旅行推荐应用程序,用户需要提供城市名称来获取该地点的所有信息。

UILabel : We will call it topLabel. We won’t need it.

UILabel:我们将其称为topLabel。 我们不需要它。

UITextField: It’s the field that we will customize to have an autocomplete search field, so let’s call it searchTextField.

UITextField:这是我们将自定义为具有自动完成搜索字段的字段,因此我们将其称为searchTextField。

UIButton : It’s the button that will be pressed when the user will find the place that they want. Let’s call it searchButton.

UIButton:当用户找到他们想要的位置时将被按下的按钮。 我们称之为searchButton

The tableView will be added programmatically so that you will see how to set it up in any kind of situation.

tableView将以编程方式添加,因此您将看到如何在任何情况下进行设置。

To have a beautiful render, I added an UIImageView on the background with a wonderful beach image.

为了获得漂亮的渲染效果,我在背景上添加了UIImageView并带有精美的海滩图像。

To connect all those components to our View Controller, select each of them and drag their reference using (Control (or Ctrl) ⌃ + Click) to your main View Controller swift file.

要将所有这些组件连接到我们的View Controller,请选择它们中的每一个,然后使用( 控制(或Ctrl)⌃ +单击 )将它们的引用拖到您的View Controller主swift文件中。

2.配置我们的CustomSearchTextField类 (2. Configure our CustomSearchTextField class)

To create our new class, we create a new file called CustomSearchTextField.swift. It’s in this class, that inherits from UITextField, that we will embed all the features that we need to implement our autocompletion search field.

为了创建我们的新类,我们创建了一个名为CustomSearchTextField.swift的新文件 在继承自UITextField的此类中,我们将嵌入实现自动完成搜索字段所需的所有功能。

使用结果创建TableView: (Creating the TableView with the results:)

To be able to show the completion results, we need to instantiate a UITableView that will display the most relevant results as below:

为了能够显示完成结果,我们需要实例化一个UITableView来显示最相关的结果,如下所示:

To do so we need to create a tableView object and then add it to the current view. In order to handle this new object, we need to override specific methods as shown below. All of the code needed to build the searchTableView will be handled by this method: buildSearchTableView().

为此,我们需要创建一个tableView对象,然后将其添加到当前视图中。 为了处理这个新对象,我们需要重写特定的方法,如下所示。 构建searchTableView所需的所有代码都将通过以下方法处理: buildSearchTableView()

Instantiating the tableView is as simple as creating a new UITableView object, but in order to access all of the functionalities of this new tableView object, we need to inherit from the TableViewDelegates and the TableViewDataSource methods. It is important to pay attention to two important variables:

实例化tableView就像创建一个新的UITableView对象一样简单,但是要访问此新tableView对象的所有功能,我们需要继承TableViewDelegates和TableViewDataSource方法。 重要的是要注意两个重要的变量:

  • The tableView delegate: This variable will let us specify which object of the view needs to be informed when some changes occur in the tableView (in our case, this object is our SearchTextField which is in this context the self object)

    tableView委托:此变量将让我们指定在tableView中发生某些更改时需要通知视图的哪个对象(在我们的例子中,该对象是我们的SearchTextField,在这种情况下,它是self对象)

  • The tableView DataSource: This variable will let us specify how all the components of the tableView will be created and from which data. Here again, we need to set it to self.

    tableView DataSource:此变量将使我们指定如何创建tableView的所有组件以及从中获取数据。 再次在这里,我们需要将其设置为self

Setting those two variables allows us to handle some actions related to the UITableView within our CustomSearchTextField class.

设置这两个变量使我们能够处理与CustomSearchTextField类中的UITableView相关的某些操作。

Now that the table view is created, we need to add data in it, and more concretely, this data will be stored into cells. We use methods inherited from the TableViewDataSource class to configure our cells and to add them to the tableView. In addition to this, the TableViewDelegates’ method will allow us to trigger where the user clicks and will print the content of the corresponding cell in the console.

现在已经创建了表视图,我们需要在其中添加数据,更具体地说,此数据将存储到单元格中。 我们使用从TableViewDataSource类继承的方法来配置单元格并将其添加到tableView。 除此之外,TableViewDelegates的方法将允许我们触发用户单击的位置,并在控制台中打印相应单元格的内容。

But if you try to run the code above, nothing will happen because the tableView frame is not set and we didn’t bring the view to the front. In order to fix this, we now need to add a updateTableView() method:

但是,如果您尝试运行上面的代码,则不会发生任何事情,因为未设置tableView框架,并且我们没有将视图置于最前面。 为了解决这个问题,我们现在需要添加一个updateTableView()方法:

Our TableView is set and is now supposed to work perfectly! But at this time we have to add data in our dataList if we want to display something. To do it simply for now, we will just add dummy data to our list: the text that the user enters in our search bar.

我们的TableView已设置好,现在应该可以正常工作了! 但是此时,如果要显示某些内容,则必须在dataList中添加数据。 现在暂时要做的是,我们只将虚拟数据添加到列表中:用户在搜索栏中输入的文本。

But the main goal of all of this is to give our users autocompletion results while they are typing in our search bar, so we need to observe when the user types a new letter and to update the tableView data according to that.

但是,所有这些操作的主要目的是在用户在搜索栏中键入内容时为其提供自动补全结果,因此我们需要观察用户何时键入新字母并据此更新tableView数据。

As you can see above, we modified the willMove() method in order to set how to handle each of the user interactions with the textField. The one that interests us is when the text field changes (when the user is typing). So each time that this action is activated, we add data to our list and we update our tableView.

如您在上面看到的,我们修改了willMove()方法,以设置如何处理与textField的每个用户交互。 我们感兴趣的是文本字段更改时(用户输入时)。 因此,每次激活此操作时,我们都会将数据添加到列表中,并更新tableView。

改善用户体验: (Improving the user experience:)

Even if our searchField doesn’t search at all, you must have seen that when we type and the results are starting to show up, all of the results are in plain text. This doesn’t look that much like an autocompletion search bar. To be more user-friendly, it would be nice to highlight the part of the text that we already typed in the text field and also to filter the results so that they correspond to what we are actually typing. Let’s do this ?

即使我们的searchField根本不搜索,您也必须已经看到,当我们键入内容并开始显示结果时,所有结果都是纯文本格式。 这看起来不像自动补全搜索栏。 为了更加用户友好,最好突出显示我们已经在文本字段中键入的文本部分,并对结果进行过滤,以使其与我们实际键入的内容相对应。 让我们做这个吗?

It’s time to create our filter method. This method will filter the relevant items from the dataList (the ones corresponding to what the user starts typing). We will use NSMutableAttributedString class to be able to highlight the part of the text that the user typed in the text field.

是时候创建我们的过滤器方法了。 此方法将从dataList中过滤相关项目(与用户开始键入的内容相对应的项目)。 我们将使用NSMutableAttributedString类来突出显示用户在文本字段中键入的文本部分

First, we create a SearchItem class that will represent each of our filtered results. As we are building our wonderful travel recommendation app, we will consider that those items are city names. Here is the SearchItem class:

首先,我们创建一个SearchItem类,该类将代表我们的每个过滤结果。 在构建出色的旅行推荐应用程序时,我们将考虑这些项目为城市名称。 这是SearchItem类:

We now need to change our global variable and to add a new one to store our filtered items:

现在,我们需要更改全局变量,并添加一个新变量来存储过滤后的项目:

Then let’s create our filter method:

然后让我们创建过滤器方法:

By converting our string to an NSString, we can use the method range() that returns the range of the first occurrence of a given string within the string. By using this method we both know if the string corresponds to what the user is typing and the position of the corresponding string! That’s all we need to highlight this part of our item. We do this using setAttributes methods and we then add our item to the resultsList. Finally, we reload the data in our tableView.

通过将字符串转换为NSString ,我们可以使用range()方法返回给定字符串在字符串中首次出现的范围。 通过使用此方法,我们都知道字符串是否与用户键入的内容相对应以及相应字符串的位置! 这就是我们需要突出显示本部分的全部内容。 我们使用setAttributes方法执行此操作,然后将项目添加到resultsList中。 最后,我们将数据重新加载到tableView中。

Let’s create new test data to try our implementation:

让我们创建新的测试数据来尝试实现:

Everything should work perfectly, we’re almost done! ?

一切都应该正常工作,我们差不多完成了! ?

3.对CoreData进行查询 (3. Make queries to CoreData)

It’s nice to have a beautiful search bar with a custom table view to display our autocompletion filtered results, but without data, it’s not very useful ?.

拥有一个漂亮的带有自定义表格视图的搜索栏来显示我们的自动补全过滤结果非常好,但是如果没有数据,那不是很有用吗?

Let’s connect our search text field to CoreData storage.

让我们将搜索文本字段连接到CoreData存储。

创建一个CoreData数据库: (Create a CoreData database:)

In order to store our persistent data, we will create a new entity (table) in our database with two attributes (rows). To do so we click to the .xcdatamodeld file in the file explorer and create a new entity named Cities, add the two attributes that we need: cityName and countryName.

为了存储持久数据,我们将在数据库中创建一个具有两个属性(行)的新实体(表)。 为此,我们单击文件浏览器中的.xcdatamodeld文件并创建一个名为Cities的新实体,添加我们需要的两个属性:cityName和countryName。

Then we will modify the type of our dataList in CustomSearchField.swift to be a list of Cities instead of a list of SearchItems:

然后,我们将CustomSearchField.swift中 dataList的类型修改为城市列表,而不是SearchItems列表:

var dataList : [Cities] = [Cities]()

对创建的数据库进行查询: (Make queries to the created database:)

Now we need to create some methods to handle the saving and the fetching of new data in the database. To do so we need to create a context. The context is a specific zone where we will store all of our changing before committing them to the database. If you use git, this is like the staging zone. You first add your file to the staging area, and when you are ready with your changes you commit them to your git.

现在我们需要创建一些方法来处理数据库中新数据的保存和获取。 为此,我们需要创建一个上下文。 上下文是一个特定区域,在将所有更改提交到数据库之前,我们将在其中存储所有更改。 如果使用git,则这类似于暂存区。 首先,将文件添加到暂存区域,并在准备好更改后将其提交到git。

We change the beginning of our filter() method in order to query the data that corresponds to the user input instead of fetching all the data from the database:

我们更改filter()方法的开头,以便查询与用户输入相对应的数据,而不是从数据库中获取所有数据:

The last thing to add is a new addData() method to populate our database. Be careful, this function needs to be called only one time as the data stored will become persistent, so comment the corresponding line in your code (just before the creation of the tableView in buildSearchTableView() ) after the first call! Even if the app is restarted, the data will still be available in the internal memory of the device.

最后要添加的是用于填充数据库的新addData()方法。 注意,此函数仅需调用一次,因为存储的数据将变为持久性,因此在第一次调用之后,注释代码中的相应行(就在buildSearchTableView()中创建tableView之前)。 即使重新启动应用程序,数据仍将在设备的内部存储器中可用。

而已 ! 我们完成了! ? (That’s it ! We’re done ! ?)

I started to dive into Swift programming a few weeks ago with an interesting MOOC that I found on Udemy. After I had acquired the basics of Swift and Xcode development, I began to work on my own projects with all of the useful documentation that I found on the web. This first tutorial is an opportunity for me to share all that knowledge that I acquired, so I hope that it has helped you!

几周前,我开始在Udemy上找到一个有趣的MOOC,开始涉足Swift编程。 在掌握了Swift和Xcode开发的基础知识之后,我开始使用我在网上找到的所有有用文档来从事自己的项目。 第一个教程是我分享我所获得的所有知识的机会,所以我希望它对您有所帮助!

If you have a question don’t hesitate to tell me in the comments! And don’t forget to give me a clap if you enjoyed the article ???

如果您有任何疑问,请随时在评论中告诉我! 而且,如果您喜欢这篇文章,别忘了给我一个鼓掌?

All the final project code is available here:

所有最终项目代码都可以在这里找到:

sinitame/customSearchField-mediumSource code for Medium article : How to create an autocompletion UITextField using CoreData in Swift …github.com

sinitame / customSearchField-medium 中级文章的源代码:如何在Swift中使用CoreData创建自动完成的UITextField… github.com

翻译自: https://www.freecodecamp.org/news/how-to-create-an-autocompletion-uitextfield-using-coredata-in-swift-dbedad03ea3d/

如何在Swift中使用CoreData设置有用的自动完成UITextField相关推荐

  1. 如何在Swift中创建漂亮的iOS图表

    通过图形和图表呈现数据是当今移动应用程序最显着的特征之一.iOS图表使应用程序看起来更漂亮,更有吸引力. 在本教程中,我们将向您展示如何使用代码示例在Swift中实现我们的iOS图表.我们将看一下Sw ...

  2. 如何在Swift中发出HTTP请求?

    本文翻译自:How to make an HTTP request in Swift? I read The Programming Language Swift by Apple in iBooks ...

  3. 如何在Swift中串联或合并数组?

    本文翻译自:How do I concatenate or merge arrays in Swift? If there are two arrays created in swift like t ...

  4. 浅层学习与深层学习_深层副本与浅层副本-以及如何在Swift中使用它们

    浅层学习与深层学习 by Payal Gupta 通过Payal Gupta 深层副本与浅层副本-以及如何在Swift中使用它们 (Deep copy vs. shallow copy - and h ...

  5. 如何在 Swift 中进行错误处理

    作者:Olivier Halligon,原文链接,原文日期:2015-12-17 译者:JackAlan:校对:靛青K:定稿:Channe 今天的文章讲解如何在 Swift 中进行错误处理. 说实话, ...

  6. 如何在Swift中使用Result

    Result介绍 Swift标准库的Result类型使我们能够使用单个统一类型来表达给定操作的结果(无论成功还是失败).让我们看一下在哪种情况下Result可能有用的方法,以及一些在开始使用该类型时要 ...

  7. 如何在WordPress中为用户设置自定义头像(Gravatar替代)

    Have you ever wanted to set custom avatars for users who leave comments with no Gravatar? Or want to ...

  8. swft c 语言 数组,如何在swift中实现数组的深拷贝

    在Objective-C中如果想将一个数组赋值给另外一个数组,同时想让两个数组之间相互独立(即改变其中的一个数组,不影响另外的一个),有很多的办法,比如我们可以直接copy,用类方法创建新数组.这样得 ...

  9. 如何在Windows中调整鼠标设置

    The old Windows properties window has been around for a long time. In Windows 8 and 10, it probably ...

最新文章

  1. ajax response.write 执行失败_Day 42:一人分饰三角,初识AJAX
  2. 【业务知识】企业数字档案馆总体架构图
  3. ibatis 高速缓存
  4. Java web application——基础
  5. 【金三银四】启动mysql服务器
  6. webapi找到了与该请求匹配的多个操作
  7. 你正在学 Web 自动化测试?Selenium 基本操作你了解嘛? | 原力计划
  8. foreman架构的引入3-安装Foreman1.5.3架构(all-in-one)
  9. 阶段5 3.微服务项目【学成在线】_day01 搭建环境 CMS服务端开发_04-项目概述-技术栈和开发步骤...
  10. 超级终端连接华为交换机_win8系统教你实现用超级终端连接华为交换机的超详细图文教程...
  11. iOS dSYM小结
  12. 第一个 DCMTK 程序:显示 DICOM 图像(DCMTK 3.6.4 + Qt 5.14.2 + VS2015)
  13. 企业盈利能力五大指标之:总资产收益率
  14. [LeetCode]739. 每日温度
  15. java基础提升(二):多线程、线程安全、线程状态、等待唤醒机制、线程池
  16. 2021-05-02 收心继续
  17. 量子计算机是哪个国家研制出来,万万没想到:最强大量子计算机居然由工业巨头研制出来了...
  18. python特殊符号
  19. android立体3D效果_PS教程:铝膜气球字制作的完整教程,3D立体效果字体的制作...
  20. 【C++】memset函数

热门文章

  1. 【今日CV 视觉论文速览】15 Nov 2018
  2. Nginx学习之十四-GDB调试Nginx初试
  3. 实例方法 java 1614780086
  4. css 背景属性 0302
  5. 前端开发 html常用标签 0229
  6. mongodb备份还原
  7. ECS上配置FTP Filezilla
  8. [转]双线性插值(Bilinear interpolation)
  9. vsftp 虚拟用户测试
  10. C++ STL标准模板库(queue)