Swift:UISearchBar:单击搜索按钮时获取文本

时间:2014-07-17 00:00:17

标签: ios swift cocoa-touch uikit uisearchbar

我正在玩Swift来学习它,而且我现在无法从UISearchBar获取文本

现在我的代码看起来像这样:

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet var myWebView : UIWebView
    @IBOutlet var adressbar: UISearchBar

    override func viewDidLoad() {
        super.viewDidLoad()

        adressbar.showsScopeBar = true

        var url = NSURL(string: "http://google.com")
        var request = NSURLRequest(URL: url)

        myWebView.scalesPageToFit = true
        myWebView.loadRequest(request)
    }

    func searchBarSearchButtonClicked( searchBar: UISearchBar!) {

        var url = NSURL(string: adressbar.text)
        var request = NSURLRequest(URL: url)

        myWebView.scalesPageToFit = true
        myWebView.loadRequest(request)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

3 个答案:

答案 0 :(得分:29)

viewDidLoad中,您必须将搜索栏的代理设置为从中接收searchBarSearchButtonClicked

import UIKit

class SecondViewController: UIViewController, UISearchBarDelegate
{
    @IBOutlet var myWebView : UIWebView
    @IBOutlet var adressbar: UISearchBar

    override func viewDidLoad()
    {
        super.viewDidLoad()

        adressbar.showsScopeBar = true
        adressbar.delegate = self

        var url = NSURL(string: "http://google.com")
        var request = NSURLRequest(URL: url)

        myWebView.scalesPageToFit = true
        myWebView.loadRequest(request)
    }

    func searchBarSearchButtonClicked( searchBar: UISearchBar!)
    {
        var url = NSURL(string: searchBar.text)
        var request = NSURLRequest(URL: url)

        myWebView.scalesPageToFit = true
        myWebView.loadRequest(request)
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }
}

答案 1 :(得分:2)

1.首先要遵守UISearchbarDelegate。

2.将搜索栏委托设置为self。

您可以在Swift iOS tutorial : Implementing search using UISearchBar and UISearchBarDelegate

找到更多相关信息

答案 2 :(得分:0)

通过搜索到达此处的人的简单(非特定)答案:

如果您的UISearchBar的出口名称为'searchBar'...

@IBOutlet weak var searchBar: UISearchBar!

然后用户在UISearchBar中输入的文本称为...

searchBar.text

Swift编码人员忘记的两件事: 1.确保添加UISearchBarDelegate类...

ViewController: UIViewController, UISearchBarDelegate
  1. 别忘了将您的视图类标识为委托... 在viewDidLoad内,您可以编写...

    searchBar.delegate = self
    

如果您忘记了上面的#1,您将无法自动完成需要实现的方法,例如...

func searchBarSearchButtonClicked(_ seachBar: UISearchBar) { your code }

...委托协议给您的。