开发者

How do I programmatically change text attributes in a WebView?

I need to highlight certain segments of text within a WebView. Until now, I've been doing this by injecting javascript into the webview using [webView stringByEvaluatingJavaScriptFromString:jscript]. The javascript adds a tag to the text in which I change the background color to yellow. This usually works but sometimes I corrupt the html when the tag is inserted. I would rather开发者_如何学Go use the - (void)changeAttributes:(id)sender method on WebView, which, as I understand, will apply the style in a way that won't break the underlying html. To do this I first call

[webView searchFor:aString direction:YES caseSensitive:NO wrap:YES];

To set the selection in the webview. Then I call

[webView changeAttributes:self];

When I send this message to my WebView instance, it invokes this method:

- (NSDictionary *)convertAttributes:(NSDictionary *)attributes {
   NSMutableDictionary *newAttrs = [[NSMutableDictionary alloc] initWithDictionary:attributes];
   NSColor *background = [NSColor yellowColor];
   [newAttrs setValue:background forKey:NSBackgroundColorAttributeName];
   return newAttrs;

}

Which should change the background color of the selected text to yellow, but it does not. Do standard Cocoa text attributes apply to a webview? Is this method intended to be used for this purpose, or should I go back to javascript?


These attributes are those for NSFonts. As described in this document, the sequence of events is usually this:

  1. [text/webView changeAttributes:obj] is performed. Usually it's done by obj itself.
  2. text/webView passes the font attributes to obj using [obj convertAttributes:...].
  3. obj returns the attributes as it wants.
  4. text/webView sets the font attributes accordingly.

Anyway I won't recommend this approach. I assume you're on OS X, not on iOS. Then, I would suggest you to get the DOM elements using WebFrame's DOMDocument and set the styles directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜