【问题标题】:WebView Insert / Modify Content dynamicallyWebView 动态插入/修改内容
【发布时间】:2011-03-15 11:53:15
【问题描述】:

在我的应用程序中,我使用 WebView 来显示内容, 现在是否可以动态修改内容,需求是这样的,

我将从网络获取信息,根据它们我需要设置样式/字体/属性,或者我可能需要在连接的设备没有响应时附加新文本,

到目前为止,我正在使用以下代码,

-(void)modifyString:(NSString *)string{
   [sourceString stringByAppendingString:errorString :string] 
}

   -(void)reloadPage{

     [[pWebView mainFrame] loadHTMLString:htmlString baseURL:nil];
    }

我认为它的实现方式不正确,我正在尝试使用

[pWebView replaceSelectionWithMarkupString:@"<html><body><p>Hi there </p></br></body></html>”];

但没有显示任何内容,因为我没有选择并且选择我的问题是 如何设置选择?

亲切的问候

罗汉

【问题讨论】:

    标签: cocoa webview nsview


    【解决方案1】:

    没关系 用这种方法解决了
    在 AwakeFromNib 方法中,添加如下代码,

    -(void)awakeFromNib{
    
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"about:blank"]];
    
        //URL Requst Object
        NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    
        //Load the request in the UIWebView.
        [[pWebView mainFrame ]loadRequest:requestObj];
        [pWebView setEditable:YES];
        [pWebView setNeedsDisplay:YES];
    
    }
    

    并添加了这个函数来追加body元素,

    -(void)appendTagToBody:(NSString *)tagName InnerHTML:(NSString *)innerHTML
    {
        // Gets a list of all <body></body> nodes.
        DOMNodeList *bodyNodeList = [[[pWebView mainFrame] DOMDocument] getElementsByTagName:@"body"];
    
        // There should be just one in valid HTML, so get the first DOMElement.
        DOMHTMLElement *bodyNode = (DOMHTMLElement *) [bodyNodeList item:0];
    
        // Create a new element, with a tag name.
        DOMHTMLElement *newNode = (DOMHTMLElement *) [[[pWebView mainFrame] DOMDocument] createElement:tagName];
    
        // Add the innerHTML for the new element.
        [newNode setInnerHTML:innerHTML];
    
        // Add the new element to the bodyNode as the last child.
        [bodyNode appendChild:newNode];
    }
    

    每当想要更改内容时,

    -(void)appendString:(NSString *)pString{
        [self appendTagToBody:@"div" InnerHTML:@"<div><p> Hi there </p></div>"];
        [self setNeedsDisplay:YES];
    }
    

    【讨论】:

    • 这似乎不会导致在&lt;head&gt; 中添加了&lt;script&gt; 标记的脚本加载。
    猜你喜欢
    • 2015-06-25
    • 2012-03-19
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    相关资源
    最近更新 更多