如何使UITextField在Swift中表现得像UISearchBar? [英] How to make UITextField behave like a UISearchBar in Swift?

查看:215
本文介绍了如何使UITextField在Swift中表现得像UISearchBar?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我正在使用UITableView和Swift中的UISearchBar开发新的应用程序,它已经正常工作了。但由于最终项目必须有一个完整的自定义搜索栏,因为定制的可能性,我不得不转移到UITextField作为输入Outlet。

Hi guys I am working on an new App using UITableView and a UISearchBar in Swift and it's already working fine. But since the final project must have a complete customized searchbar, I had to move to UITextField as the input Outlet because of the customization possibilities.

问题是我可以弄清楚如何编码,以便UITextField的行为类似于UISearchBar。不知道如何过滤UITextField输入并使字符串可用于UISearchBarDelegate方法。

The problem is that I just can't figure out how to code so that the UITextField behaves like a UISearchBar. Have no idea of how I could filter the UITextField inputs and make the string usable with the UISearchBarDelegate methods.

所以任何人都可以帮我解决这个问题?

So anyone could help me out with this?

编辑:我听了Daniel的帮助,想出了这个代码,但是它返回nil,没有工作。

I followed Daniel's help and came up with this code, but it is returning "nil", not working.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

@IBOutlet weak var txtSearchBar: UITextField!
var searchTxt = ""
let prods = ["água", "terra", "ar", "fogo"]
var searchResults:[String] = []

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    txtSearchBar.delegate = self
}


func textFieldDidEndEditing(textField: UITextField) {
    searchTxt = textField.text
    println(searchTxt)
    searchResults = prods.filter({(produtos:String) -> Bool in

        let nameMatch = produtos.rangeOfString(self.searchTxt, options: NSStringCompareOptions.CaseInsensitiveSearch)

        println(nameMatch)
        return nameMatch != nil})
}

我的输入是字母ar,但它返回nil,因为它不应该是因为数组的一个对象是ar。

My input was the letters "ar" but it returned "nil", when it shouldn't since one of the array's object is "ar".

推荐答案

在@Daniel T.的帮助下,我设法通过以下代码解决了问题:

With the help of @Daniel T. I managed to solve the problem with the following code:

func textFieldShouldReturn(textField: UITextField) -> Bool {
    isFiltered = true
    searchResults = prods.filter({(coisas:String) -> Bool in
        let stringMatch = coisas.rangeOfString(textField.text)
        return stringMatch != nil

    })
    println(searchResults.description)
    textField.resignFirstResponder()
    table.reloadData()
    return true
}

谢谢@Daniel T。

Thanks @Daniel T.

这篇关于如何使UITextField在Swift中表现得像UISearchBar?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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