如何使用 Swift 在 WebView 中查找和突出显示文本

哑光

我正在开发我的第一个应用程序,它涉及从网站上的大量文本中搜索特定的文本字符串。我希望能够搜索特定字符串并突出显示所有实例,并且随着用户键入更多内容,它会自动更新突出显示的事件。类似于任何浏览器中的查找功能。

在这里找到了这个问题,他们引用使用 UIWebViewSearch.js 来实现这一点,但我不确定如何将该文件添加到我的项目中,或者如何使用它。

到目前为止,我已经在我的应用程序中添加了一个搜索栏,但还没有对它做任何事情。想用这个功能和搜索栏一起搜索文本。

这是我的 ViewController 代码:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var searchBar: UISearchBar!

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

    // Place custom HTML onto the screen
    let myURL = Bundle.main.url(forResource: "myHTML", withExtension: "html")
    let requestObj = URLRequest(url: myURL!)
    webView.loadRequest(requestObj)


    // Code that provides a string containing
    // JS code, ready to add to a webview.
    if let path = Bundle.main.path(forResource: "UIWebViewSearch", ofType: "js"),
        let jsString = try? String(contentsOfFile: path, encoding: .utf8) {
        print(jsString)
    } // end if


    func searchBarSearchButtonClicked() {
        let startSearch = "uiWebview_HighlightAllOccurencesOfString('\(str)')"

        self.newsWebView .stringByEvaluatingJavaScript(from: startSearch)
    }


} // end of viewDidLoad


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
} // end of didReceiveMemoryWarning


} // end of class ViewController
波茨克

正如@jon-saw 所说:欢迎使用 StackOverflow :)

我只会回答你如何将 JavaScript 文件添加到你的项目中......这应该能让事情开始:)

添加文件

您可以通过多种方式将文件添加到 Xcode,但这里是一种。

  1. 在 Xcode 中,在您的项目中,在左侧的项目导航器中导航到您想要添加文件的位置。

选择位置

  1. 右键单击并选择“新建文件...”

新文件

  1. 选择“空”,然后单击“下一步”

在此处输入图片说明

  1. 命名您的文件UIWebViewSearch.js,然后单击“创建”

  2. 您现在UIWebViewSearch.js在项目中调用一个空文件,您可以在其中粘贴内容。

使用文件

现在您的项目中有该文件,所以现在您只需要引用它。为此,您可以使用Bundlewhich 可以为您加载项目中的资源。

If you look at the answer you referred to, you can see these lines of ObjC code in - (NSInteger)highlightAllOccurencesOfString:(NSString*)str

NSString *path = [[NSBundle mainBundle] pathForResource:@"UIWebViewSearch" ofType:@"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

Translated to Swift that would look like this:

if let path = Bundle.main.path(forResource: "UIWebViewSearch", ofType: "js"),
   let jsString = try? String(contentsOfFile: path, encoding: .utf8) {
    print(jsString)
}

And that should give you a String containing all your JS code, ready to add to a WebView for instance.

Hope that gives you something to start with.

Update (after you added a comment to this post)

OK, so you say:

I added my ViewController code to better communicate where I'm at. Kind of confused on how to implement the second part of his code you're referring to. Also not sure how to call the search from the searchBar. Is there a method I need to call within 'searchBarSearchButtonClicked()' method? Just found that method on the apple developer documentation, don't know if it's the correct one, though.

Lets break it down into pieces, I'll start with your ViewController, as there are some problems in your viewDidLoad:

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

    // Place custom HTML onto the screen
    let myURL = Bundle.main.url(forResource: "myHTML", withExtension: "html")
    let requestObj = URLRequest(url: myURL!)
    webView.loadRequest(requestObj)
    // Code that provides a string containing
    // JS code, ready to add to a webview.
    if let path = Bundle.main.path(forResource: "UIWebViewSearch", ofType: "js"),
        let jsString = try? String(contentsOfFile: path, encoding: .utf8) {
        print(jsString)
    } // end if


    func searchBarSearchButtonClicked() {
        let startSearch = "uiWebview_HighlightAllOccurencesOfString('\(str)')"

        self.newsWebView .stringByEvaluatingJavaScript(from: startSearch)
    }
}

You've added your searchBarSearchButtonClicked inside viewDidLoad, but it should be declared as a function by itself (we'll get back to it later).

Furthermore, as I wrote in the comments below:

...One part that is run when the view is loaded and which loads the JavaScript from the bundle.

So lets fix your viewDidLoad:

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

    // Place custom HTML onto the screen
    let myURL = Bundle.main.url(forResource: "myHTML", withExtension: "html")
    let requestObj = URLRequest(url: myURL!)
    webView.loadRequest(requestObj)
    // Code that provides a string containing
    // JS code, ready to add to a webview.
    if let path = Bundle.main.path(forResource: "UIWebViewSearch", ofType: "js"),
        let jsString = try? String(contentsOfFile: path, encoding: .utf8) {
        print(jsString)
        //Use your jsString on the web view here.
        newsWebView.stringByEvaluatingJavaScript(from: jsString) 
    }
}

As you can see, the searchBarSearchButtonClicked function has been removed and we now use out jsString on the newsWebView.

OK, next part:

Also not sure how to call the search from the searchBar. Is there a method I need to call within 'searchBarSearchButtonClicked()' method? Just found that method on the apple developer documentation, don't know if it's the correct one, though.

You have your searchBarSearchButtonClicked() method which you have found in the Apple Developer documentation, I'm guessing you're meaning this one

As you can see in the documentation (top bar), this function is from the UISearchBarDelete class.

Delegation is a design pattern used in many of Apples frameworks. It allows you to write some generic components and let "someone else" (the delegate) decide what to do with the information from the component (bad explanation I know).

Think of your UISearchBar for instance. If you were to implement a component that other developers could use as a search bar, how would you handle when the user searches for something? I'm thinking, how should your "customers" (the developers using your components) handle this? One way of doing this could be that the developers should subclass UISearchBar and override a "user did search method". You could also use NSNotifications and have the developer register for these notifications. Both of these methods are not pretty or clever.

Enter...the delegate.

UISearchBar has a UISearchBarDelegate and UISearchBarDelegate is just a protocol as you can see. Now the UISearchBar can ask its delegate for certain things, or inform the delegate about important events. So for instance, when the user taps the "Search" button UISearchBar can call delegate.searchBarSearchButtonClicked(self) which means "hey delegate, the user has clicked the search button on me...just thought you should know". And the delegate can then respond as it sees fit.

This means that any class can conform to UISearchBarDelegate and handle the various tasks as it suits in their current situation.

OK, long story, hope you get the gist of it and I think you should read a bit more on delegation as it is a pattern used all over in Apples frameworks :)

So, in your case, you have a UISearchBar, you should give that a delegate like so:

searchBar.delegate = self

And you need to tell the compiler that you intend to implement the UISearchBarDelegate protocol. The Swift convention is to do this in an extension after your ViewController, just to keep things separated:

extension ViewController: UISearchBarDelegate {

}

And then you must also implement the methods of UISearchBarDelegate that you are interested in listening to (note that some protocols have required methods, meaning that you MUST implement them but I don't think UISearchBar has (otherwise you'll find out when the app crashes the first time you run it :)).

So in your case, you mentioned searchBarSearchButtonPressed. As you can see it needs a UISearchBar as a parameter. So your function ends out looking like this:

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    guard let currentSearchText = searchBar.text else {
        return
    }
    let startSearch = "uiWebview_HighlightAllOccurencesOfString('\(currentSearchText)')"

    newsWebView.stringByEvaluatingJavaScript(from: startSearch)
}

所以...您从搜索栏中获取当前文本,将其作为参数添加到您的startSearch字符串中,然后将该startSearch字符串传递给您的newsWebView.

整个扩展看起来像这样。

.... last part of your ViewController class
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    } // end of didReceiveMemoryWarning
} // end of class ViewController

extension ViewController: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        guard let currentSearchText = searchBar.text else {
            return
        }
        let startSearch = "uiWebview_HighlightAllOccurencesOfString('\(currentSearchText)')"

        newsWebView.stringByEvaluatingJavaScript(from: startSearch)
    }
}

你的viewDidLoad结果看起来像这样(你必须将自己添加为 searchBar 的委托)

override func viewDidLoad() {
    super.viewDidLoad()
    searchBar.delegate = self //delegate set up
    // Do any additional setup after loading the view, typically from a nib.

    // Place custom HTML onto the screen
    let myURL = Bundle.main.url(forResource: "myHTML", withExtension: "html")
    let requestObj = URLRequest(url: myURL!)
    webView.loadRequest(requestObj)
    // Code that provides a string containing
    // JS code, ready to add to a webview.
    if let path = Bundle.main.path(forResource: "UIWebViewSearch", ofType: "js"),
        let jsString = try? String(contentsOfFile: path, encoding: .utf8) {
        print(jsString)
        //Use your jsString on the web view here.
        newsWebView.stringByEvaluatingJavaScript(from: jsString) 
    }
} 

哇……写了很多……希望对你有帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何在 swift 中突出显示文本时触发事件

来自分类Dev

如何根据 UI 和 UX 在 WebView 中显示 pdf - iOS Swift

来自分类Dev

使用MS Word VBA如何使用突出显示颜色的值查找和替换突出显示的文本

来自分类Dev

在Swift中使用字符定界符查找并突出显示文本

来自分类Dev

在android的webview中突出显示选定的文本

来自分类Dev

Xcode-Swift-如何使用WebView控制器通过Google Image查找图像URL

来自分类Dev

Swift如何使WebView更快加载

来自分类Dev

Swift:如何仅更改<img>或webView中的图像大小

来自分类Dev

如何使用 Swift 4.2 在我的 WebView 中更改用户代理?

来自分类Dev

如何在Swift中包含表情符号的字符串中突出显示文本?

来自分类Dev

如何突出显示和使用文本框中突出显示的行?

来自分类Dev

(Android和Ios)Webview选择文本并突出显示

来自分类Dev

如何使用javascript查找和突出显示即使在某些元素中标记的文本?

来自分类Dev

如何从Webview打开Safari View Controller(Swift)

来自分类Dev

Xcode:如何在Webview中停止视频并仍在使用WebView

来自分类Dev

如何使用WebView显示React jsx文件

来自分类Dev

如何使用KitKat使文本适合WebView中的屏幕(文本换行)

来自分类Dev

如何同时使用NestedScrollView,SwipeRefreshLayout和WebView?

来自分类Dev

Swift-WebView和登录弹出窗口

来自分类Dev

Swift Webview:如何从JavaScript正确调用Swift代码?

来自分类Dev

Swift-禁用WebView中的链接

来自分类Dev

在 Swift 中从 webView 获取 html 内容?

来自分类Dev

Android Webview:如何在Webview中复制选定的文本。

来自分类Dev

使用Xcode中的Swift确定在WebView中完成网站加载

来自分类Dev

“如何在 Swift 中加载 WebView 之前从 Firebase 数据库中检索 url?”

来自分类Dev

如何查找UIImageView swift中显示的图像

来自分类Dev

如何在Android中显示WebView

来自分类Dev

如何在Swift中显示来自NSData的PDF-如何将PDF保存到文档文件夹Swift-如何在Swift中通过WebView显示来自已保存NSData的PDF

来自分类Dev

使用片段(ActionTabs)和Webview

Related 相关文章

  1. 1

    如何在 swift 中突出显示文本时触发事件

  2. 2

    如何根据 UI 和 UX 在 WebView 中显示 pdf - iOS Swift

  3. 3

    使用MS Word VBA如何使用突出显示颜色的值查找和替换突出显示的文本

  4. 4

    在Swift中使用字符定界符查找并突出显示文本

  5. 5

    在android的webview中突出显示选定的文本

  6. 6

    Xcode-Swift-如何使用WebView控制器通过Google Image查找图像URL

  7. 7

    Swift如何使WebView更快加载

  8. 8

    Swift:如何仅更改<img>或webView中的图像大小

  9. 9

    如何使用 Swift 4.2 在我的 WebView 中更改用户代理?

  10. 10

    如何在Swift中包含表情符号的字符串中突出显示文本?

  11. 11

    如何突出显示和使用文本框中突出显示的行?

  12. 12

    (Android和Ios)Webview选择文本并突出显示

  13. 13

    如何使用javascript查找和突出显示即使在某些元素中标记的文本?

  14. 14

    如何从Webview打开Safari View Controller(Swift)

  15. 15

    Xcode:如何在Webview中停止视频并仍在使用WebView

  16. 16

    如何使用WebView显示React jsx文件

  17. 17

    如何使用KitKat使文本适合WebView中的屏幕(文本换行)

  18. 18

    如何同时使用NestedScrollView,SwipeRefreshLayout和WebView?

  19. 19

    Swift-WebView和登录弹出窗口

  20. 20

    Swift Webview:如何从JavaScript正确调用Swift代码?

  21. 21

    Swift-禁用WebView中的链接

  22. 22

    在 Swift 中从 webView 获取 html 内容?

  23. 23

    Android Webview:如何在Webview中复制选定的文本。

  24. 24

    使用Xcode中的Swift确定在WebView中完成网站加载

  25. 25

    “如何在 Swift 中加载 WebView 之前从 Firebase 数据库中检索 url?”

  26. 26

    如何查找UIImageView swift中显示的图像

  27. 27

    如何在Android中显示WebView

  28. 28

    如何在Swift中显示来自NSData的PDF-如何将PDF保存到文档文件夹Swift-如何在Swift中通过WebView显示来自已保存NSData的PDF

  29. 29

    使用片段(ActionTabs)和Webview

热门标签

归档