在键入Swift时搜索 [英] Search as you type Swift

查看:96
本文介绍了在键入Swift时搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在你用Swift编写的时候实现搜索。它已经工作但我需要一些调整。我发送每个输入的字母

I try to implement Search as you type written in Swift. It works already but I need some tuning. I send with each letter typed in

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

    let debouncedFindUser = debounce(
        Static.searchDebounceInterval,
        Static.q,
        findUser)

    debouncedFindUser()
}

对后端的请求。

func findUser() -> () {
    SearchService.sharedInstance.getUser(0, numberOfItems: 100,
        searchString: searchUserBar.text.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
        ,
        success: {SearchUserDto -> Void in
            if self.searchUserBar.text != nil {
                self.updateSearch()
            }
        },
        failure: {NSError -> Void in

    })
}

我尝试了Debounce的实现在这里如何去除方法调用?

I tried an implementation of Debounce found here How can I debounce a method call?

我的问题:

如果在一定时间内触发了方法调用,我想重新启动方法调用。所以让我们夸大一点。

I want to "restart" a method call if it was triggered within a certain time. So let's exaggerate a little bit.

请求只能在搜索文本未输入2秒后才开始。因此,如果我是一个快速的typer并且每0.5秒输入一个字母,那么请求永远不会被触发,除非我暂停至少2秒。

The request shall only start after search text wasn't typed for 2 seconds. So if I'm a quick typer and type each 0.5 seconds a letter the request should never be triggered except I pause for at least 2 seconds.

推荐答案

您可以使用NSTimer。在textDidChange中启动或无效并重新启动计时器2秒钟。让计时器在实际弹出时触发findUser方法。

You could use an NSTimer. Start or invalidate and restart the timer for 2 seconds in your textDidChange. Have the timer fire the findUser method when it actually pops.

    var debounceTimer: NSTimer?

@IBAction func test() {
    if let timer = debounceTimer {
        timer.invalidate()
    }
    debounceTimer = NSTimer(timeInterval: 2.0, target: self, selector: Selector("getUser"), userInfo: nil, repeats: false)
    NSRunLoop.currentRunLoop().addTimer(debounceTimer!, forMode: "NSDefaultRunLoopMode")
}

func getUser() {
    println("yeah")
}

这篇关于在键入Swift时搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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