如何在Swift中创建自动完成文本字段 [英] How to create autocomplete text field in Swift

查看:129
本文介绍了如何在Swift中创建自动完成文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要创建的是iOS中的自动完成文本字段.

What I want to be able to create is an auto complete text field in iOS.

我有一个选择客户的表格,其中用户必须使用文本字段选择一次客户.我想发生的是,当用户在文本字段上写前三个字母时,我希望某些服务使用输入的文本来运行远程Web服务查询,并以自动完成建议的形式显示查询结果.

I have a form for selecting a client, wherein the user must select a client once using a text field . What I want to happen is when the user writes the first three letters on the text field, I want some service to run a remote web service query using the entered text and present the query results as auto complete suggestions.

以下是我当前用于我的应用的代码(仅适用于iPad).

Below is my current code for my app (iPad only).

   import UIKit

    class AddClientViewController: UIViewController, UITextFieldDelegate {

        @IBOutlet weak var clientTextField:  UITextField!

        var foundList = [String]()


    override func viewDidLoad() {
        super.viewDidLoad()



         let listUrlString =  "http://bla.com/myTextField.php?field=\(clientTextField)"
        let myUrl = NSURL(string: listUrlString);
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "GET";

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil {
                print(error!.localizedDescription)
                dispatch_sync(dispatch_get_main_queue(),{
                    AWLoader.hide()

                })

                return
            }


            do {

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray

                if let parseJSON = json {


                    self.foundList = parseJSON as! [String]

                }


        } catch {

            print(error)

        }
    }

    task.resume()
}

这是我的Web服务提供的json输出.

Here is the json output that my web service provides.

["123,John", "343,Smith", "345,April"]

以逗号分隔,第一个参数是client ID,第二个参数是客户端的名称. John是名称,因此应在自动完成建议中显示,如果选择该名称,则会将clientTextField的文本设置为John.

Separated by commas, the first parameter is the client ID and the second parameter is the name of the client. John is the name so it should be presented in the auto complete suggestions, which if selected will set the text of the clientTextField to John.

clientTextField的当前文本内容作为GET参数传递到我的Web服务.

The current text content of the clientTextField is passed as a GET parameter to my webservice.

我不知道该怎么做.该用户可能正在打字但尚未完成,而可能已经发送了多个查询.

I don't know how to do this. The user could be typing and not yet finished, while multiple queries could already have been sent.

推荐答案

我在我的应用程序中做了类似的操作来查找联系人.我将对此进行伪编码,以供您理解概念:

I did something like this in my app for looking up contacts. I will pseudo code this out for you to understand the concept:

1)捕获最终用户在文本字段中输入的字符

2)输入的某些字符数决定查询服务器以返回所有匹配的条目-选择您喜欢的字符数(我选择了3-4个字符).更少的回报,更多的回报却不那么明显...取决于您,性能和用户体验的考虑.

3)将服务器查询的结果放入客户端的数组中.这是您的超集,您将从中为用户提供建议.

4)在每个随后的字符输入到文本字段之后,您现在将通过输入到此点的字符串来过滤数组(array.filter()). 5)tableView.reloadData()针对输入的每个字符过滤后的数组.

6)我使用dataFlag变量来确定要在表视图中显示的数据源,具体取决于用户的操作.

1) Capture the characters entered into the textfield by the enduser

2) At some character count entered decide to query the server to return all entries that match - choose the character count you are comfortable with (I chose around 3-4 characters). Fewer returns more, more returns less obviously...up to you, perf and UX considerations.

3) Put the results of this server query into an array on the client. This will be your superset from which you will offer the suggestions to the user.

4) After each subsequent character entered into the text field you will now filter the array (array.filter()) by character string entered to this point. 5) tableView.reloadData() against the filtered array at each character entered.

6) I use a dataFlag variable to determine what datasource to show in the tableview depending on what the user is doing.

注意:您只查询服务器一次,以最大程度地降低性能影响

Note: You only query the server once to minimize perf impact

// this function is called automatically when the search control get user focus
func updateSearchResults(for searchController: UISearchController) {
  let searchBar = searchController.searchBar
  if searchBar.text?.range(of: "@") != nil {
    self.getUserByEmail(searchBar.text!)
  }
  if searchController.searchBar.text?.characters.count == 0 && dataFlag != "showParticipants" {
    dataFlag = "showInitSearchData"
    self.contacts.removeAll()
    self.participantTableView.reloadData()
  }
  if dataFlag == "showInitSearchData" && searchController.searchBar.text?.characters.count == 2 {
    self.loadInitialDataSet() {
      self.dataFlag = "showFilteredSearchData"
    }
  }
  if dataFlag == "showFilteredSearchData" {
    self.filterDataForSearchString()
  }

}

// filter results by textfield string
func filterDataForSearchString() {
  let searchString = searchController.searchBar.text
  self.filteredContacts =  self.contacts.filter({
    (contact) -> Bool in
    let contactText: NSString = "\(contact.givenName) \(contact.familyName)" as NSString

  return (contactText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound
  })

  DispatchQueue.main.async {
    self.participantTableView.reloadData()
  }  
}

这篇关于如何在Swift中创建自动完成文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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