开发者

iPhone: How to Display Text from UIWebView HTML Document in a UITextView

开发者 https://www.devze.com 2022-12-23 12:20 出处:网络
I have an RSS feed that gets arranged in a UITableView which lets the user select a story that loads in a UIWebView. However, I\'d like to stop using the UIWebView and just use a UITextView or UILabel

I have an RSS feed that gets arranged in a UITableView which lets the user select a story that loads in a UIWebView. However, I'd like to stop using the UIWebView and just use a UITextView or UILabel.

This png is what I am trying to do (just display the various text aspects of a news story):

iPhone: How to Display Text from UIWebView HTML Document in a UITextView

I have tried using:

NSString *myText = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];

and assigning the string to a UILabel but it doesn't work from where I am implementing it in webViewDidFini开发者_运维技巧shLoad (--is that not the proper place?). I get a blank textView and normal webView.

If I overlay a UITextView on top of a UIWebView on its own (that is, a webView that just loads one page), the code posted above works displays the text fine. The problem arises when I try to process the RSS feed .

I've been stuck wondering why this doesn't work as it should for a few days now. If you have a better, more efficient way of doing it then placing the code in webViewDidFinishLoad, please let me know! Does it go in my didSelectRowAtIndexPath?

Thank you very much in advance!


I think the you should first log the string returned by :

NSString *myText = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];

... in the case of the RSS feed to make sure that you are getting something back. It's possible the RSS page doesn't have the same javascript components and that it returns an empty string.

Once you've confirmed that, then it becomes a simple matter of getting it to display properly in the text view.


If the NSString you want to display is not empty, try to do something like this in the webViewDidFinishLoad method:

[yourUILabel performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:@"bla bla %@", @"more bla"] waitUntilDone:YES];

The main thread of an iphone app is responsible for drawing components, that is why your label doesn't show your text.

You could also try setting setNeedsDisplay: to true

Also, the UILabel will not preserve the HTML format. It will display it as just text.


You could try the following:

NSString *htmlContent = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML;"];

NSString *htmlContent = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML;"];

NSString *htmlContent = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerText;"];

You lose out on formatting information with the last line of code.

0

精彩评论

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